0

在此处输入图像描述我正在使用以下代码在 iphone 中创建画笔。

@interface Canvas : UIImageView {
    CGPoint location;
}

@property CGPoint location;
.m file
@synthesize location;

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];   
    self.location = [touch locationInView:self];    
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentLocation = [touch locationInView:self];  

    UIGraphicsBeginImageContext(self.frame.size); 
    CGContextRef ctx = UIGraphicsGetCurrentContext();  
    //CGContextSetBlendMode(ctx, kCGBlendModeOverlay);


    [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextSetBlendMode(ctx, kCGBlendModeNormal);
    CGContextSetLineWidth(ctx, 5.0);
    CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
    //CGContextSetBlendMode(ctx, kCGBlendModeOverlay);
    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, location.x, location.y);
    CGContextAddLineToPoint(ctx, currentLocation.x, currentLocation.y);
    CGContextStrokePath(ctx);
    self.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    location = currentLocation;
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentLocation = [touch locationInView:self];

    UIGraphicsBeginImageContext(self.frame.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();  
  //  CGContextSetBlendMode(ctx, kCGBlendModeOverlay);

    [self.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    CGContextSetBlendMode(ctx, kCGBlendModeNormal);
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextSetLineWidth(ctx, 5.0);
    CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, location.x, location.y);
    CGContextAddLineToPoint(ctx, currentLocation.x, currentLocation.y);
    CGContextStrokePath(ctx);
    self.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    location = currentLocation;     
}

它正在工作,但是在绘制时,在绘制的直线上一定距离后有一些点。我想删除这些点并想要平滑的直线。我怎样才能做到这一点?

4

1 回答 1

0

您一遍又一遍地使用相同的图像,将它与旧图像相乘,对吗?我会尝试在每次触摸时使用新的上下文。然后将其乘以现有图像。也许这就是奇怪的样子的原因?

如果起点和终点不同,您也可以添加检查。

你应该做一个额外的绘图方法。TouchesMoved 和 TouchesEnded 中有多余的代码。

于 2012-04-19T13:22:09.107 回答