我的任务是制作一个类似橡皮擦工具(用手指操作),它会显示一个背景图像,而不是被擦除的图像。
这是我的源图像和目标图像(只是为了测试,实际的图像可能不同):
http://img232.imageshack.us/img232/6030/29572847.png
以下是我的代码。创建模式:
如果本地变量revealAlpha的值为1.0(如最后一段代码所示),则一切正常。但我需要擦除半透明(这样用户需要在同一位置多次滑动才能完全擦除它)。问题就在这里。如果我使revealAlpha小于1.0,则显示的目标图像看起来会出现错误。以下是revealAlpha == 1.0和revealAlpha == 0.1的结果:
这是我的源图像和目标图像(只是为了测试,实际的图像可能不同):
![image1](https://istack.dev59.com/EJIiM.webp)
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
if(revealPattern) CGPatternRelease(revealPattern);
CGPatternCallbacks callbacks = { 0, &patternCallback, NULL};
revealPattern = CGPatternCreate(self, self.bounds, CGAffineTransformIdentity, self.bounds.size.width, self.bounds.size.height, kCGPatternTilingConstantSpacing, true, &callbacks);
}
模式回调函数(**info*包含指向*self*的指针):
void patternCallback(void *info, CGContextRef context) {
CGRect rect = ((DrawView *)info).bounds;
CGImageRef imageRef = ((DrawView *)info).backgroundImage.CGImage;
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, rect, imageRef);
}
绘制方法如下:
- (void)drawPoints:(CGContextRef)context{
if([points count] < 2) return;
CGPoint lastPoint = [[points objectAtIndex: 0] CGPointValue];
CGContextBeginPath(context);
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGColorSpaceRef revealPatternSpace = CGColorSpaceCreatePattern(NULL);
CGContextSetStrokeColorSpace(context, revealPatternSpace);
CGFloat revealAlpha = 1.0;
CGContextSetStrokePattern(context, revealPattern, &revealAlpha);
CGContextSetAlpha(context, 0.1);
CGColorSpaceRelease(revealPatternSpace);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineWidth(context, self.lineWidth);
for(int i = 1; i < [points count]; i++){
CGPoint currPoint = [[points objectAtIndex: i] CGPointValue];
CGContextAddLineToPoint(context, currPoint.x, currPoint.y);
lastPoint = currPoint;
}
CGContextStrokePath(context);
}
如果本地变量revealAlpha的值为1.0(如最后一段代码所示),则一切正常。但我需要擦除半透明(这样用户需要在同一位置多次滑动才能完全擦除它)。问题就在这里。如果我使revealAlpha小于1.0,则显示的目标图像看起来会出现错误。以下是revealAlpha == 1.0和revealAlpha == 0.1的结果:
http://img593.imageshack.us/img593/1809/69373874.png
如果你仔细观察,你会注意到右侧图片上的蓝色渐变不再平滑。