Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

objective c - Draw a circle when clicked using quartz

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);
}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...