【问题标题】:CGcontext drawing on image not working在图像上绘制的 CGcontext 不起作用
【发布时间】:2016-02-12 08:14:53
【问题描述】:

这是我的代码,它在执行时会产生非常奇怪的绘图。此外,通过图像视图,图像开始慢慢消失。请帮我解决这个问题

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];

//    if ([touch tapCount] == 2)
//    {
//        imageView.image = nil;
//    }

location = [touch locationInView:touch.view];
lastClick = [NSDate date];

lastPoint = [touch locationInView:self.view];
lastPoint.y -= 0;

[super touchesBegan:touches withEvent:event];
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{mouseSwiped = YES;

UITouch *touch = [touches anyObject];
currentPoint = [touch locationInView:self.view];

UIGraphicsBeginImageContext(imageView.image.size);

[imageView.image drawInRect:CGRectMake(0, 44, imageView.image.size.width, imageView.image.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);

CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 1, 0, 1);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());

imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
 //   lastPoint = currentPoint;


}

而且,它所画的线条形状怪异,而且还在不断消失

【问题讨论】:

    标签: ios objective-c cgcontext touchesbegan touchesmoved


    【解决方案1】:

    您的图像正在移动,因为您在每次重绘时将偏移硬编码为 44 点。

    奇怪的绘图很可能是无效坐标系使用的结果。您在视图坐标中接收触摸位置,但在图像坐标中绘制。解决此问题的最简单方法是创建大小等于视图大小而不是图像大小的上下文。只需使用imageView.bounds.size 而不是imageView.image.size。请注意,我假设您在图像视图中使用“缩放填充”模式。

    修改后的完整绘制代码:

    UIGraphicsBeginImageContext(self.imageView.bounds.size);
    
    [self.imageView.image drawInRect:CGRectMake(0, 0, self.imageView.bounds.size.width, self.imageView.bounds.size.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
    
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 1, 0, 1);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), self.lastPoint.x, self.lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    
    self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    此外,您的解决方案在性能方面并不是最优的。我建议在视图中单独绘制路径,而不是在每次触摸移动时更新 imageView 图像。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多