Reputation: 6109
I am drawing an rectangle using tutorial at here
FlagClass.m
-(void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextMoveToPoint(context, 100, 100);
CGContextAddLineToPoint(context, 150, 150);
CGContextAddLineToPoint(context, 100, 200);
CGContextAddLineToPoint(context, 50, 150);
CGContextAddLineToPoint(context, 100, 100);
CGContextStrokePath(context);
}
@end
Then I am adding this view to another view like below
-(IBAction)drawRectangle {
FlagClass *flag = [[FlagClass alloc] initWithFrame:CGRectMake(20.0, 100.0, 80, 40)];
[self.view addSubview:flag];
}
After clicking on the button, what I got is
My question :
drawRect
methoddrawRect
Please help if you have any ideas about it.
Upvotes: 0
Views: 92
Reputation: 31782
Because of the dimensions of your view (the FlagClass
instance), all of your drawing is going on outside of the visible bounds (the view is "clipping" the blue rectangle). The black rectangle you're seeing is the default background fill of UIView.
To get what you want, you could adjust the frame of your subview so it's large enough to contain the stroked path. Or change the coordinates you're using to draw; those are the numbers in the calls to CGContextAddLineToPoint
. Here's one way to at least see what you're doing (while removing the black background):
FlagClass *flag = [[FlagClass alloc] initWithFrame:CGRectMake(20.0, 100.0, 250, 250)];
flag.backgroundColor = [UIColor clearColor];
[self.view addSubview:flag];
By changing the width and height of the subview (the 3rd and 4th parameters to CGRectMake
), the subview becomes large enough to contain the square being drawn.
Upvotes: 2