使用Objective-C的Cocoa Touch时,我正在寻找一种最佳方法来绘制目标图像(即圆圈内的圆圈,足够简单),然后记录用户在图像上的触摸(可能是x或+标记),更重要的是,记录在内存中以便于之后重新绘制。当用户长时间按下手指以获得更精确的位置时,我将使用放大镜,我通过阅读和实验了解了这一点,参考了CoffeeShopped 的文章和源代码。
- (void)drawRect:(CGRect)rect {
CGRect circleRect = self.bounds;
CGFloat circleWidth = circleRect.size.width / 5.0;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
CGContextFillEllipseInRect(context, circleRect);
circleRect = CGRectInset(circleRect, circleWidth, circleWidth);
CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGContextFillEllipseInRect(context, circleRect);
circleRect = CGRectInset(circleRect, circleWidth, circleWidth);
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
CGContextFillEllipseInRect(context, circleRect);
}
将绘制
你应该将视图的backgroundColor设置为[UIColor clearColor]
,以使其在边缘处不是黑色。
你也可以将其调整为循环,但这是我能展示的最简单的示例代码。
注意:为了简化arc/nonarc代码,我没有重用颜色。
如果您想重复使用该图像并重新绘制它(例如-当用户触摸它时),您应该将该绘图缓存为图像。
1)绘制您的目标(如下所述)
2)从当前上下文创建图像
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
3)保存该图像,下次重复使用
- (void)drawRect:(CGRect)rect {
if(image == nil) {
image = [self drawTargetImage]; //use code that mentioned below to create image
}
[image drawAtPoint:CGPointMake(10, 10)];
}