Draw a circle when clicked using quartz

天大地大妈咪最大 提交于 2019-12-12 06:58:05

问题


I want a circle to be drawn when the user clicks anywhere on the screen. Whats missing/is wrong with this code?

- (void)drawRect:(CGRect)rect
{
if (UITouchPhaseBegan)
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 0, 0, 225, 1);
    CGContextSetRGBFillColor(context, 0, 0, 255, 1);
    CGRect rectangle = CGRectMake(50, 50, 500, 500);
    CGContextStrokeEllipseInRect(context, rectangle);
}

}

回答1:


Your code doesn’t do what you think it does. Have a look at the definition of UITouchPhaseBegan in UITouch.h:

typedef NS_ENUM(NSInteger, UITouchPhase) {
    UITouchPhaseBegan,             // whenever a finger touches the surface.
    UITouchPhaseMoved,             // whenever a finger moves on the surface.
    UITouchPhaseStationary,        // whenever a finger is touching the surface but hasn't moved since the previous event.
    UITouchPhaseEnded,             // whenever a finger leaves the surface.
    UITouchPhaseCancelled,         // whenever a touch doesn't end but we need to stop tracking (e.g. putting device to face)
};

It’s just an enum value, not a reflection of what is going on in your app. I believe that in this case, because it is the first value in the enum, it is probably being set to 0 by the compiler, and is therefore always evaluating to false.

What you probably want to do is to set an ivar like BOOL _touchHasbegun;. Then, in -touchesBegan:withEvent or your gesture recognizer action, depending on how you’re doing touch handling, set _touchHasBegun to YES or NO as appropriate.

When you know your view needs to be updated, call [self setNeedsDisplay] (or [self setNeedsDisplayInRect:someRect] if you can, for better performance) to trigger the -drawRect: method. Then, have your -drawRect: method check whether _touchHasBegun to determine whether to draw your circle.

Note: You should never call -drawRect: yourself. You set the view as dirty, and the OS takes care of drawing it at the right time.



来源:https://stackoverflow.com/questions/15076306/draw-a-circle-when-clicked-using-quartz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!