dev*_*guy 19 objective-c draw touches ios
我有一个小应用程序,允许用户用手指在屏幕上绘图.我有一个UIImageView用户绘制的地方,通过创建CGContextRef和各种CG draw功能.我主要用函数绘制笔画/线条CGContextAddLineToPoint
现在我的问题是:用户可以绘制各种颜色的线条.我想让他能够使用"rubber"工具用手指删除到目前为止绘制的图像的某些部分.我最初做这个用白色的笔触(设置与CGContextSetRGBStrokeColor功能),而是因为我后来发现它不工作了... UIImage在UIImageView实际上有一个透明背景,不用白...所以我会最后是透明的图像,上面有白线!
无论如何设置一个"transparent"笔触颜色还是有其他方法来清除CGContextRef用户手指下的内容,当他移动它时?谢谢
小智 58
这样就可以了:
CGContextSetBlendMode(context, kCGBlendModeClear)
Run Code Online (Sandbox Code Playgroud)
我最终使用了Bresenham的线算法(当我不得不编写自己的图形例程时,回到过去的日子)......
- (void) contextEraseLine:(CGContextRef) ctx from:(CGPoint)startPoint to:(CGPoint) endPoint withThickness:(int)thickness {
int x, cx, deltax, xstep,
y, cy, deltay, ystep,
error, st, dupe;
int x0, y0, x1, y1;
x0 = startPoint.x;
y0 = startPoint.y;
x1 = endPoint.x;
y1 = endPoint.y;
// find largest delta for pixel steps
st = (abs(y1 - y0) > abs(x1 - x0));
// if deltay > deltax then swap x,y
if (st) {
(x0 ^= y0); (y0 ^= x0); (x0 ^= y0); // swap(x0, y0);
(x1 ^= y1); (y1 ^= x1); (x1 ^= y1); // swap(x1, y1);
}
deltax = abs(x1 - x0);
deltay = abs(y1 - y0);
error = (deltax / 2);
y = y0;
if (x0 > x1) { xstep = -1; }
else { xstep = 1; }
if (y0 > y1) { ystep = -1; }
else { ystep = 1; }
for ((x = x0); (x != (x1 + xstep)); (x += xstep))
{
(cx = x); (cy = y); // copy of x, copy of y
// if x,y swapped above, swap them back now
if (st) { (cx ^= cy); (cy ^= cx); (cx ^= cy); }
(dupe = 0); // initialize no dupe
if(!dupe) { // if not a dupe, write it out
//NSLog(@"(%2d, %2d)", cx, cy);
CGContextClearRect(ctx, CGRectMake(cx, cy, thickness, thickness));
}
(error -= deltay); // converge toward end of line
if (error < 0) { // not done yet
(y += ystep);
(error += deltax);
}
}
}
Run Code Online (Sandbox Code Playgroud)
唷!要创建一个(有点)笨重的橡皮擦线还有很长的路要走.
要使用它,请执行以下操作:
- (void)eraseStart {
// erase lines
UIGraphicsBeginImageContext(drawingBoard.size);
ctx = UIGraphicsGetCurrentContext();
CGContextDrawImage(ctx,CGRectMake(0,0,drawingBoard.size.width, drawingBoard.size.height),[drawingBoard CGImage]);
}
- (void)eraseEnd {
drawingBoard = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[drawingView removeFromSuperview];
[drawingView release];
drawingView = [[UIImageView alloc] initWithImage:drawingBoard];
drawingView.frame = CGRectMake(intEtchX, intEtchY, intEtchWidth, intEtchHeight);
[self.view addSubview:drawingView];
}
Run Code Online (Sandbox Code Playgroud)
这假设您已经创建了一个drawingView(UIImageView)和drawingBoard(UIImage).
然后,要删除一行,只需执行以下操作:
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self eraseStart];
[self contextEraseLine:ctx from:CGPointMake (x1, y1) to:CGPointMake (x2, y2) withThickness:10];
[self eraseEnd];
Run Code Online (Sandbox Code Playgroud)
(用适当的值替换x1,y1,x2和y2)...
| 归档时间: |
|
| 查看次数: |
12453 次 |
| 最近记录: |