我需要改进我的“drawRect”方法。这太慢了。我有 10 个透明 png,我想将它们与不同的混合模式合并在一起。我读过来自Apple Developer Lib和Stackoverflow的帖子。
现在我想知道如何改进我的代码和整体绘图性能。请你帮助我好吗?在 for 循环中加载所有这些图像会很慢,对吧?我如何获得最大的性能?
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform matrix =CGContextGetCTM(context);
CGAffineTransformInvert(matrix);
CGContextConcatCTM(context,matrix);
CGRect contentRect;
// load each UIImage
for (i=0; i< [configurationArray count]; i = i + 1) {
image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:nil]];
contentRect = CGRectMake(x,y,image.size.width,image.size.height);
CGContextSetBlendMode (context, kCGBlendModeScreen);
CGContextSetAlpha (context, [layerData.layerAlpha floatValue]);
CGContextDrawImage (context,contentRect, image.CGImage);
}
}
更新:
现在我正在使用 CALayers 将像素直接放在所需的位置。但我需要不同的混合模式、阿尔法和颜色填充每一层。有没有办法避免在每一层上调用昂贵的“CGContextDrawImage”方法?例如,我希望它可以只更新特定层的小尺寸的上下文,对吗?或者我是否需要为每个上下文更改渲染整个 UIView?
我希望有人能把我推向正确的方向。我只需要学习那个主题。谢谢你的帮助。
- (void)drawRect:(CGRect)rect {
// load each UIImage
for (int i=0; i< [myArray count]; i++) {
image = [[ImageCache sharedImageCache] imageForKey:imageName];
CALayer* sublayer = [CALayer layer] ;
[sublayer setPosition:CGPointMake(image.size.width/2, image.size.height/2)];
[sublayer setFrame:CGRectMake(x, y, image.size.width, image.size.height)];
CGImageRef layerImage = [image CGImage];
[sublayer setContents:(__bridge id) layerImage];
[sublayer setBackgroundColor:[[UIColor clearColor] CGColor]];
[self.layer addSublayer:sublayer];
// How can i set the blend mode, color fill & alpha value without
// calling the expensive "CGContextDrawImage" ? Possible?
}
}