2

我在我的应用程序中实现了一个突出显示功能。此高亮显示在 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;
}
4

1 回答 1

1

我不能确切地告诉你为什么会出现这些伪影,但是......

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

您可能想尝试使用 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];

如有必要,shouldRasterizelayer 属性可能有助于提高性能:

self.layer.shouldRasterize = YES;

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

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

于 2012-07-28T12:38:13.167 回答