我已经在我的应用程序中实现了突出显示功能。此突出显示是在UIImage中绘制的,因此可以将其另存为PNG表示形式。一切工作正常,但是最近我意识到了一个非常令人困惑的问题。有时,当我强调时,图纸被扭曲了。看起来是这样的:

每当我移动手指突出显示字符时,绘制的突出显示就会向左延伸。另一个:

在这一步中,每当我移动手指以突出显示时,绘制的突出显示都在向上移动!

这一切都让我感到困惑。有时会发生这种情况,有时只发生在某些页面上。有时它会像这样正常工作:

我很困惑为什么会这样。谁能告诉我或者至少让我知道为什么会这样?请帮我。

代码:

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

   for (int r = 0; r < [rectangles count]; r++)
   {
      CGRect rect = [[rectangles objectAtIndex:r]CGRectValue];

      //Get the edges of the rectangles
      CGFloat xEdge = rect.origin.x + rect.size.width;
      CGFloat yEdge = rect.origin.y + rect.size.height;

    if ((currPoint.x > rect.origin.x && currPoint.x < xEdge) && (currPoint.y < rect.origin.y && currPoint.y > yEdge))
    {
        imgView.image = [self drawRectsToImage:imgView.image withRectOriginX:rect.origin.x originY:rect.origin.y rectWidth:rect.size.width rectHeight:rect.size.height];
        break;
    }
   }
}

//The function that draws the highlight
- (UIImage *)drawRectsToImage:(UIImage *)image withRectOriginX:(CGFloat)x originY:(CGFloat)y rectWidth:(CGFloat)width rectHeight:(CGFloat)ht
{
  UIGraphicsBeginImageContext(self.bounds.size);
  CGContextRef context = UIGraphicsGetCurrentContext();
  [image drawInRect:self.bounds];

  CGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);

  CGRect rect = CGRectMake(x, y, width, ht);
  CGContextAddRect(context, rect);
  CGContextSetCMYKFillColor(context, 0, 0, 1, 0, 0.5);
  CGContextFillRect(context, rect);

  UIImage *ret = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return ret;
}

最佳答案

我无法确切告诉您为什么会出现这些假象,但是...

我认为在触摸处理程序中渲染图像不是一个好主意。触摸处理应尽可能少。

您可能想尝试使用CoreAnimation的CALayer:

像这样将您的图像设置为背景图像(假设您的类是UIView的子类)或使用实际的UIImageView:

self.layer.contents = (id)image.CGImage;

当您检测到另一个矩形rect被触摸时,将突出显示添加为图像背景上方的子层:
CALayer *highlightLayer = [CALayer layer];
highlightLayer.frame = rect;
highlightLayer.backgroundColor = [UIColor yellowColor].CGColor;
highlightLayer.opacity = 0.25f;
[self.layer addSublayer:highlightLayer];

必要时shouldRasterize图层属性可能有助于提高性能:
self.layer.shouldRasterize = YES;

为了使用所有这些,请使用QuartzCore框架并将<QuartzCore/QuartzCore.h>导入您的实现文件中。

您可以通过将self.layer渲染到图像上下文中来创建图层层次结构的PNG表示,然后获取图像和PNG表示。

07-28 02:37
查看更多