UITouches 屏幕绘图

本文详细介绍了如何使用TouchView类收集触摸事件并将其绘制为路径。通过在TouchView中实现touchBegan、touchMoved和drawRect方法,可以实现在触摸屏上绘制由一系列点组成的路径。代码示例展示了如何收集触摸点、保存到数组并在视图中绘制线条。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

与手势一样,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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值