【问题标题】:QuartzCore performance on clear UIView清晰 UIView 上的 QuartzCore 性能
【发布时间】:2011-01-16 14:11:23
【问题描述】:

我有一个 UIView,我在 init 方法中将背景颜色设置为清除。然后我在drawRect中的2个点之间画一条蓝线。第一个点是视图上的第一次触摸,第二个点在调用 touchesMoved 时发生更改。

这样线的一端是固定的,而另一端随着用户的手指移动。然而,当背景颜色清晰时,线条会有很大的延迟并会跳过(不平滑)。

如果我将背景颜色更改为黑色(只是取消对 setbackgroundcolor 行的注释),那么运动会更加平滑,并且看起来很棒,除了你看不到它后面的视图。

我该如何解决这个问题? (在iPad上,我只有模拟器,目前还没有接入设备)所以性能流畅,但背景清晰,可以看到背景视图。

-(id) initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

-(void) drawRect:(CGRect)rect {
if (!CGPointEqualToPoint(touchPoint, CGPointZero)) {
    if (touchEnded) {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextClearRect(context, rect);
    } else {

CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    CGContextSetLineWidth(context, 3.0f);
    CGFloat blue[4] = {0.0f, 0.659f, 1.0f, 1.0f};
    CGContextSetAllowsAntialiasing(context, YES);
    CGContextSetStrokeColor(context, blue);
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
    CGContextAddLineToPoint(context, touchPoint.x, touchPoint.y);
    CGContextStrokePath(context);

    CGContextSetFillColor(context, blue);

    CGContextFillEllipseInRect(context, CGRectMakeForSizeAroundCenter(CGSizeMake(10, 10), touchPoint));
    CGContextFillEllipseInRect(context, CGRectMakeForSizeAroundCenter(CGSizeMake(10, 10), startPoint));
    }   
    }
}



-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.touchEnded = NO;
    if ([[touches allObjects] count] > 0) 
        startPoint = [[[touches allObjects] objectAtIndex:0] locationInView:self];
        touchPoint = [[[touches allObjects] objectAtIndex:0] locationInView:self];
    [self setNeedsDisplay];
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    self.touchEnded = NO;
    if ([[touches allObjects] count] > 0) 
        touchPoint = [[[touches allObjects] objectAtIndex:0] locationInView:self];
    [self setNeedsDisplay];
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    self.touchEnded = YES;
    [self setNeedsDisplay];
    [self removeFromSuperview];
}
- (void)dealloc {
    [super dealloc];
}

【问题讨论】:

    标签: objective-c ipad quartz-graphics


    【解决方案1】:

    首先,您应该在设备上测试性能,而不是在模拟器中。大多数与图形相关的东西在模拟器中的工作方式非常不同,有些快得多,有些则慢得多。

    也就是说,如果透明背景确实证明是设备上的性能问题,则很可能是因为您使用CGContextClearRect() 填充了太多像素。我能想到两个解决方案:

    • touchesBegan:withEvent: 中,您可以使用CALayer 的renderInContext: 方法制作底层视图的快照,并将快照绘制为背景而不是清除它。这样您就可以让视图保持不透明,从而节省将视图与其下方的视图合成的时间。
    • 您可以创建一个单点高的 CALayer 来表示一条线,并将其转换为 touchesMoved:withEvent:,使其末端位于正确的位置。代表线端的点也是如此(CAShapeLayer 非常适合)。会涉及一些难看的三角函数,但性能会非常出色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      相关资源
      最近更新 更多