我有一个UIImage我在它上面画了一条跟随用户手指的线条。它就像一块绘图板。当UIImage很小时(例如500 x 600),这非常有效,但如果它像1600 x 1200那样,它会变得非常沙哑和迟钝。有没有办法可以优化这个?这是我在touchesModed中的绘图代码:
UIGraphicsBeginImageContext(self.frame.size);
[drawImageView.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 15.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
//CGContextSetAlpha(UIGraphicsGetCurrentContext(), 0.5f);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
感谢。
答案 0 :(得分:0)
不是一次性绘制整个1600X1200帧,为什么不在需要时绘制它。我的意思是,因为你正在绘制整个框架(驻留在内存中),你的表现不尽如人意。
试试CATiledLayer。基本上你需要绘制一个只有你的设备才能使用的屏幕尺寸,除了用户滚动你需要动态绘制它之外的任何东西。
这是iPad或iPhone上的Google地图中使用的内容。希望这会有所帮助...
答案 1 :(得分:0)
每次触摸移动时,不是创建新的上下文并将当前图像绘制到其中,而是使用CGBitmapContextCreate
创建上下文并重用该上下文。之前的所有绘图都已经在上下文中,每次触摸移动时您都不必创建新的上下文。
- (CGContextRef)drawingContext {
if(!context) { // context is an instance variable of type CGContextRef
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
if(!colorSpace) return nil;
context = CGBitmapContextCreate(NULL, contextSize.width, contextSize.height,
8, contextSize.width * 32, colorSpace,
kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
if(!context) return nil;
CGContextConcatCTM(context, CGAffineTransformMake(1,0,0,-1,0,contextSize.height));
CGContextDrawImage(context, (CGRect){CGPointZero,contextSize}, drawImageView.image.CGImage);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 15.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
}
return context;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGContextRef ctxt = [self drawingContext];
CGContextBeginPath(ctxt);
CGContextMoveToPoint(ctxt, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(ctxt, currentPoint.x, currentPoint.y);
CGContextStrokePath(ctxt);
CGImageRef img = CGBitmapContextCreateImage(ctxt);
drawImageView.image = [UIImage imageWithCGImage:img];
CGImageRelease(img);
}
此代码需要实例变量CGContextRef context
和CGSize contextSize
。无论何时更改大小,都需要在dealloc中释放上下文。