0

我创建了一个 UIView 子类,并使用 UIBezierpath 绘制圆角矩形并用一些渐变填充它。

简而言之,这是子类 draw rect 的样子:

CGRect frame1 = //size of Frame 1

CGRect frame2 = //size of Frame 2



//gradientingStart
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

if (options == false) {
    self.color = [self createRandomColor];
}



NSArray *gradientColors = [NSArray arrayWithObjects:
                           (id)[UIColor colorWithHue:color saturation:saturationVal brightness:brightnessVal alpha:1].CGColor,
                           (id)[UIColor colorWithHue:color+0.04 saturation:saturationVal+0.15 brightness:brightnessVal-0.15 alpha:1].CGColor, nil];

CGFloat gradientLocations2[] = {0.25,1};
CGGradientRef gradient2 = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations2);
CGContextSaveGState(context);
//gradientingEnd

UIBezierPath *result =
[UIBezierPath bezierPathWithRoundedRect: frame1 cornerRadius:radius];
[result appendPath:
 [UIBezierPath bezierPathWithRoundedRect: frame2 cornerRadius:radius]];
[result setLineWidth:3];
[[UIColor blackColor]setStroke];
[result stroke];
[result fill];
[result addClip];
CGContextDrawLinearGradient(context, gradient2, CGPointMake(0, 0), CGPointMake(0, self.bounds.size.height), 0);

//important to prevent leaks
CGGradientRelease(gradient2);
CGColorSpaceRelease(colorSpace);
//-------
UIImage *texture = [UIImage imageNamed:@"texture2.png"];
[texture drawInRect:CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, self.bounds.size.height)];

现在我在我的视图控制器中创建了几个这样的实例,并尝试使用这样的动画来移动它们:

[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{
    costumview.alpha = 0;
    [costumview setFrame:CGRectMake(320,0,320,420)];
    [self reorderViewsFrom:costumview.intValue];
    overlay.alpha = 0;
}completion:^(BOOL finished){
}];

但不幸的是,动画在设备上非常滞后,显示的服装视图越多(5-10),效果就越差。

如何提高性能并提供流畅的动画?我认为改变服装视图不是一种选择,因为这会破坏应用程序的感觉。有没有更快的方法来为服装视图设置动画?

4

2 回答 2

1

您的 drawRect 方法非常激烈。绘制这些渐变和圆角边缘是性能繁重的例程,并且因为您在动画中更改图像的帧,所以您的 drawRect 经常被调用。

我会在你的绘制矩形中添加一个 NSLog,看看当你为自定义视图设置动画时它被调用了多少次。你可能会感到惊讶。

您可以尝试使用:

view.layer.shouldRasterize = YES

通过这种方式,您可以在设置动画之前渲染自定义视图的位图。再次为帧更改设置动画后,您应该再次调用 drawRect 并禁用 shouldRasterize。

在此处阅读有关 shouldRasterize 的更多信息:

https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CALayer_class/Introduction/Introduction.html#//apple_ref/occ/instp/CALayer/shouldRasterize

于 2012-08-16T16:41:57.233 回答
0

I pointed out that using some CALayer transformation (rounding corners) causing the lag - unfournately this wasn't in the snippet I posted.

I avoided it by creating the rounded corners with a own uiview subclass. This makes the app a lot smoother. All these rasterization stuff didn't do it for me...

于 2012-08-31T00:22:57.547 回答