我想让我的应用以触摸坐标为中心绘制一个圆。
这是我现在拥有的代码,它肯定是乱七八糟的,我没有任何关于绘图和使用上下文的练习。我在这里错过了什么?提前致谢。
View Controller 是 UIViewController 的子类
@implementation ViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *theTouch = [touches anyObject];
[self doSomething];
//[self.view setNeedsDisplay];
}
- (void) drawCircleAtPoint:(CGPoint)point withRadius:(CGFloat)radius inContext:(CGContextRef)context{
UIGraphicsPushContext(context);
CGContextBeginPath(context);
CGContextAddArc(context, point.x, point.y, radius, 0, 2*M_PI, YES);
CGContextFillPath(context);
UIGraphicsPopContext();
}
- (void)drawRect:(CGRect)rect
{
CGPoint point;
CGContextRef context = UIGraphicsGetCurrentContext();
point.x = self.view.bounds.origin.x + self.view.bounds.size.width/2;
point.y = self.view.bounds.origin.y + self.view.bounds.size.height/2;
CGContextSetLineWidth(context, 5.0);
[[UIColor whiteColor] setFill];
[self drawCircleAtPoint:point withRadius:50 inContext:context];
}
@end
在这里,我希望它至少在屏幕中心绘制圆圈,但我连这个都做不到。
最佳答案
drawRect 是 UIView 类的一个方法。 它在 ViewController 中不可用,因此不会被调用。
理想情况下,您应该做的是将 drawRect 和 drawCircleAtPoint 放在 UIView 子类中。 还要在该 View 类中添加 touches 方法。 您可以将其命名为 DrawCircleView 或其他名称。
现在创建这个自定义 View 的对象,并将其作为 subview 添加到 viewDidLoad 中的 View Controller View 中。
在 touches 方法中调用 setNeedsDisplay 并将 touvh 的点存储在 CGPoint 实例变量中,并在 drawRect 中访问它。
更新
您可能想要保存之前绘制的圆圈。
有很多可能性,选择最适合你的,我没有给你详细的解释,但有足够的信息让你开始。
如果您希望圆是可编辑的,那么您将必须继续添加关于圆心和半径的圆信息作为一个 NSMutableArray 中的对象。 在 drawRect 的开头,您将不得不循环重绘它们。
事实上,我建议您使用 CGPath 并继续向该路径添加圆圈 并将路径添加到 drawRect 中的 cgcontext 保持 CGPath 作为实例变量,以便它保留来自上次 drawRect 调用的先前信息。 但是如果你想用不同的颜色绘制圆圈,那么它们必须在不同的 CGPaths 中 然后您可以再次将对象中带有颜色信息的 CGPath 添加到可变数组中。
或
- 如果数组不断增长,保存并重新绘制所有这些圆圈将影响性能。如果您不想撤消功能或不想编辑以前的圈子。 然后,您可以将 drawRect 末尾绘制的任何内容保存为 imageData,然后将其保存为实例 var 并在每次调用 drawRect 时重新绘制它,然后在其顶部绘制一个圆圈并将图像再次保存到同一实例中。
例如:在 drawRect 的末尾,您可以将屏幕图像保存到实例变量中 _savedImage。
_savedImage = UIGraphicsGetImageFromCurrentImageContext();
并且在 drawRect 开始重绘时,如果 _savedImage 不为 nil 那么,
[_savedImage drawInRect:rect];
然后您可以围绕您点击的点绘制圆圈。 此外,如果您愿意,您可以随时将绘图保存到实际图像文件中:
NSData *imageData = UIImagePNGRepresentation(_savedImage);
[imageData writeToFile:@"imageName.png"];
或
- 如果你愿意,你可以探索
CGContextSaveGState() 和 CGContextRestoreGState()
它们分别用于将上下文压入和弹出堆栈。 所以你可以得到最后的上下文并重新绘制它,在恢复和保存之间你可以画你的圆圈。查看此 stackOverflow 帖子:Saving and restoring CGContext
关于iOS 5 - 触摸画一个圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10742694/