【问题标题】:Draw a circle when clicked using quartz使用石英点击时画一个圆圈
【发布时间】:2013-02-25 20:54:06
【问题描述】:

我希望在用户单击屏幕上的任意位置时绘制一个圆圈。这段代码缺少什么/有什么问题?

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

}

【问题讨论】:

    标签: objective-c cocoa-touch quartz-graphics


    【解决方案1】:

    您的代码并没有按照您的想法执行。看看UITouch.hUITouchPhaseBegan的定义:

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

    这只是一个枚举值,而不是反映您的应用中正在发生的事情。我相信在这种情况下,因为它是枚举中的第一个值,它可能被编译器设置为 0,因此总是评估为 false。

    您可能想要做的是设置一个像BOOL _touchHasbegun; 这样的ivar。然后,在 -touchesBegan:withEvent 或您的手势识别器操作中,根据您进行触摸处理的方式,将 _touchHasBegun 设置为 YES 或 NO。

    当你知道你的视图需要更新时,调用[self setNeedsDisplay](或[self setNeedsDisplayInRect:someRect],如果可以的话,以获得更好的性能)来触发-drawRect:方法。然后,让你的-drawRect:方法检查是否_touchHasBegun来决定是否画你的圆圈。

    注意:你永远不应该自己打电话给-drawRect:。您将视图设置为脏视图,操作系统会负责在正确的时间绘制它。

    【讨论】:

    • 当 _touchHasBegun 时如何使 -drawRect 方法检查?
    • 当 _touchHasBegun 时如何使 -drawRect 检查?
    • 修改了我的答案以包括使用-setNeedsDisplay-setNeedsDisplayInRect:
    • setNeedsDisplay 应该放在哪里?
    • 任何时候你知道视图需要更新。您使用的是-touchesBegan:withEvent 及其兄弟姐妹,还是手势识别器?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    相关资源
    最近更新 更多