您必须子类化UIView
并覆盖drawRect:
方法,将CGContextRef
你得到UIGraphicsGetCurrentContext
无效于drawRect:
方法,并且不要建立对图形上下文的强引用,因为它可能会在对 drawRect: 方法的调用之间发生变化。
当您识别出捏合手势时,将 CGPoint 传递给视图并发送setNeedsDisplay
的方法。
总是使用setNeedsDisplay
要刷新视图,请勿发送drawRect:
直接地。
线视图.m
- (void)drawRect:(CGRect)rect
{
// p1 and p2 should be set before call `setNeedsDisplay` method
[self drawRect:location1 Loc2:location2] ;
}
- (void)drawRect:(CGPoint)location1 Loc2:(CGPoint)location2 {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = {0.0, 0.0, 1.0, 1.0};
CGColorRef color = CGColorCreate(colorspace, components);
CGContextSetStrokeColorWithColor(context, color);
CGContextMoveToPoint(context, location1.x, location1.y);
CGContextAddLineToPoint(context, location2.x, location2.y);
CGContextStrokePath(context);
CGColorSpaceRelease(colorspace);
CGColorRelease(color);
}
编辑:我假设你只有在两根手指放在一起时才画线。
- (void)handleLinePinch:(UIPinchGestureRecognizer *)gesture
{
NSUInteger num_touches = [gesture numberOfTouches];
// save locations to some instance variables, like `CGPoint location1, location2;`
if (num_touches == 2) {
location1 = [gesture locationOfTouch:0 inView:l];
location2 = [gesture locationOfTouch:1 inView:l];
}
// you need save location1 and location2 to `l` and refresh `l`.
// for example: l.location1 = location1; l.location2 = location2;
[l setNeedsDisplay];
}