我想创建一个路径。就像我触摸屏幕并在touchmove事件中绘制线条。当线条从起点开始相交时。使用任何颜色填充该路径。
现在在图像中看到我画了一条线。我只想检测线是否再次相交到起点。然后用我自己想要的颜色填充那条路径。另外我用核心图形绘制线但是它很慢在真实的设备上。你能告诉我一种提高速度的方法吗?
答案 0 :(得分:2)
部首:
#import <UIKit/UIKit.h>
@interface myView : UIView {
CGMutablePathRef path;
CGPathRef drawingPath;
CGRect start;
BOOL outsideStart;
}
@end
实现:
#import "myView.h"
@implementation myView
- (id) init {
if (self = [super init]) {
self.userInteractionEnabled = YES;
self.multipleTouchEnabled = NO;
}
}
- (void) finishPath {
if (drawingPath) {
CGPathRelease(drawingPath);
}
CGPathCloseSubpath(path);
drawingPath = CGPathCreateCopy(path);
CGPathRelease(path);
path = NULL;
[self setNeedsDisplay];
return;
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
path = CGPathCreateMutable();
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self];
start = CGRectZero;
start.origin = p;
start = CGRectInset(start,-10, -10);
outsideStart = NO;
CGPathMoveToPoint(path, NULL, p.x, p.y);
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if (!path) {
return;
}
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self];
if (CGRectContainsPoint(start,p)) {
if (outsideStart) {
[self finishPath];
}
} else {
outsideStart = YES;
}
CGPathAddLineToPoint(path,NULL,p.x,p.y);
[self setNeedsDisplay];
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (!path) {
return;
}
[self finishPath];
}
- (void) touchesCanceled:(NSSet *)touches withEvent:(UIEvent *)event {
if (!path) {
return;
}
CGPathRelease(path);
path = NULL;
}
- (void) drawInRect:(CGRect)rect {
CGContextRef g = UIGraphicsGetCurrentContext();
if (drawingPath) {
CGContextAddPath(g,drawingPath);
[[UIColor redColor] setFill];
[[UIColor blackColor] setStroke];
CGContextDrawPath(g,kCGPathFillStroke);
}
if (path) {
CGContextAddPath(g,path);
[[UIColor blackColor] setStroke];
CGContextDrawPath(g,kCGPathStroke);
}
}
- (void) dealloc {
if (drawingPath) {
CGPathRelease(drawingPath);
}
if (path) {
CGPathRelease(path);
}
[super dealloc];
}
@end
请注意,您可能希望执行某些操作,这样每次路径更改时您实际上都不会调用setNeedsDisplay。这可能会非常缓慢。建议包括使用NSTimer每隔x毫秒触发一次以检查是否需要重新显示,如果需要则重新显示,或者仅在触摸移动了很长的距离时重新绘制。
答案 1 :(得分:1)
也许它对你有用link text
答案 2 :(得分:0)
每次图像更改时,Core Graphics绝对不应该使用[self setNeedsDisplay]
,这可能是您的代码在设备上如此慢的原因。绘图很慢。如果你使用OpenGL ES绘制线条,它会更快,但代价是更难以理解。