How to make a Drawing method in a View class work using CGContextRef?
I have these 2 methods in the View class. the drawRect method always gets called when the view is initalized. But i can't get the drawLine method to work. It doesn't do anything when it gets called. Am i supposed to deal with cgimagecontext or something like that? please help!!
- (void)drawRect:(CGRect)rect {
// Drawing code
// Drawing code
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//C开发者_高级运维GContextSetRGBFillColor(contextRef, 0, 0, 255, 1);
CGContextSetRGBStrokeColor(contextRef, 0, 0, 0, 1);
CGContextSetLineWidth(contextRef, 5.0);
CGContextBeginPath(contextRef);
CGContextMoveToPoint(contextRef, 0, 0);
CGContextAddLineToPoint(contextRef, 320, 480);
CGContextStrokePath(contextRef);
}
-(void)drawLine:(CGPoint)from to:(CGPoint) to {
// Drawing code
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//CGContextSetRGBFillColor(contextRef, 0, 0, 255, 1);
CGContextSetRGBStrokeColor(contextRef, 0, 128, 0, 1);
CGContextSetLineWidth(contextRef, 5.0);
CGContextBeginPath(contextRef);
CGContextMoveToPoint(contextRef, 0, 0);
CGContextAddLineToPoint(contextRef, 320, 50);
CGContextStrokePath(contextRef);
}
Are you calling -drawLine from within -drawRect? You need to do all drawing in a view within your drawRect method. If you're calling -drawLine from somewhere else, it won't work.
You can only do drawing in drawrect. If you want to draw custom lines via your drawLine method, replace the hard-coded points in drawrect with variables. You can then set these variables in your drawLine method and finally call [self setNeedsDisplay].
精彩评论