UITouches 屏幕绘图

与手势一样,UIView 掌握直接屏幕绘图。当用户触摸屏幕时,Touchview类收集一系列点。在每个触摸移动之处,touchesMoved:WithEvent: 方法调用

setNeedsDispaly。这又会触发对drawRect:调用,其中视图将这些点绘制成线段来创建一个可视屏幕路径。

代码:

#define POINT(X)    [[self.points objectAtIndex:X] CGPointValue]

UIColor *current;

@interface TouchView : UIView
{
    NSMutableArray *points;
}
@property (retain) NSMutableArray *points;
@end

@implementation TouchView
@synthesize points;

- (BOOL) isMultipleTouchEnabled {return NO;}

// Start new array
- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event
{
    self.points = [NSMutableArray array];
    CGPoint pt = [[touches anyObject] locationInView:self];
    [self.points addObject:[NSValue valueWithCGPoint:pt]];
}

// Add each point to array
- (void) touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event
{
    CGPoint pt = [[touches anyObject] locationInView:self];
    [self.points addObject:[NSValue valueWithCGPoint:pt]];
    [self setNeedsDisplay];
}

// Draw all points
- (void) drawRect: (CGRect) rect
{
    if (!self.points) return;
    if (self.points.count < 2) return;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    [current set];
    CGContextSetLineWidth(context, 4.0f);
    
    int i = 0;
    for ( i;i < (self.points.count - 1); i++)
    {
        CGPoint pt1 = POINT(i);
        CGPoint pt2 = POINT(i+1);
        CGContextMoveToPoint(context, pt1.x, pt1.y);
        CGContextAddLineToPoint(context, pt2.x, pt2.y);
        CGContextStrokePath(context);
    }
}
@end

posted @ 2012-10-22 20:10  ip海  阅读(100)  评论(0编辑  收藏  举报