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 :
- These coordinate of my rectangle is (20,100,80,40).What are the numbers in
drawRectmethod - Why I am just getting a black rectangle instead of the blue one with defined coordinates in
drawRect
Please help if you have any ideas about it.
Because of the dimensions of your view (the
FlagClassinstance), 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):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.