通过触摸绘制 CGRect
我想知道如何将 CGRect 绘制到 UIImageView 上。这是我得到的代码,但它似乎不起作用。有什么建议吗? touch1 和 touch2 都是 CGPoint,point 是 CGRect。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
touch1 = [touch locationInView:self];
touch2 = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
touch2 = [touch locationInView:self];
point = CGRectMake(touch2.x, touch2.y, 50, 50);
[self setNeedsDisplay];
}
- (void) drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetFillColorWithColor(context, pointColor.CGColor);
CGContextAddEllipseInRect(context, point);
CGContextDrawPath(context, kCGPathFillStroke);
}
I was wondering how to draw a CGRect onto an UIImageView. Here is the code I've got but it doesn't seem to be working. Any suggestions? touch1 and touch2 are both CGPoints and point is a CGRect.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
touch1 = [touch locationInView:self];
touch2 = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
touch2 = [touch locationInView:self];
point = CGRectMake(touch2.x, touch2.y, 50, 50);
[self setNeedsDisplay];
}
- (void) drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetFillColorWithColor(context, pointColor.CGColor);
CGContextAddEllipseInRect(context, point);
CGContextDrawPath(context, kCGPathFillStroke);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您看到实际发生了什么?
一些注意事项:
touchesBegan
中,您知道touch1
和touch2
将始终设置为相同的值,对吧?您似乎从未使用过 touch1。point
是一个误导性的变量名称,表示某个矩形。drawRect
并不是没有道理的。什么是pointColor
?如果你画黑底黑字,这可能是问题的一部分。What do you see actually happening?
A few notes:
touchesBegan
, you know thattouch1
andtouch2
will always be set to the same thing, right? You don't seem to ever be using touch1.point
is a misleading variable name for something that is a rect.drawRect
is not unreasonable. What ispointColor
? If you're drawing black-on-black that might be part of the problem.清单 3-1 通过对圆应用变换来创建椭圆的代码
Quartz2d 示例
Listing 3-1 Code that creates an ellipse by applying a transform to a circle
Lots more example code in the Quartz2d Example
我只拿了你的代码,它对我有用。看看吧。感谢您的代码。在此示例中,我绘制了一个矩形。
I took your code only, its working for me. Just have look at it. And thanks for your code. In this sample i am drawing a rect.