我想在我的ViewController2中绘制一个矩形。在视图中绘制矩形
我读到我可以使用CGRect,但我找不到如何去做。
我想代表一个房间,所以我可以在我在房间里的位置放置一个点。
我已经尝试过重写的drawRect的方法,但我有一些错误
我这个代码的尝试:
// rectangle.h
#import <UIKit/UIKit.h>
@interface Rectangle : UIView
@property (nonatomic, assign) CGRect myRect;
@end
// rectangle.m
#import "rectangle.h"
@implementation Rectangle
@synthesize myRect;
- (void)drawRect:(NSRect)rect {
// Drawing code here.
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(c, 1.0, 0.0, 0.5, 1.0);
CGContextFillRect(c, myRect);
}
@end
// ViewController2.m
#import "ViewController2.h"
#import "rectangle.h"
@implementation ViewController2
// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
[super viewDidLoad];
if(![self.view isKindOfClass:Rectangle])
{
Rectangle *view = [[Rectangle alloc] initWithFrame:self.view.bounds];
self.view = view;
}
[(rectangle*)self.view setMyRect:CGRectMake(120, 120, 80, 80)];
[self.view setNeedsDisplay];
}
@end
但这不起作用
在提出基本问题之前,请尽量少做功课。 –
我修改了你列出的代码,试试。我不确定你的'self.view'是你的自定义视图类(可以在IB中设置,不知道)。在您的自定义视图的绘图代码中添加一个断点并查看它是否被调用。从那里出发。 – Putz1103