我想使用几个CALayers作为UIViewController的子层。 第一个是背景。
其他人都在这个背景之前。
如何组合/绘制带孔/透明点的图像 并在CALayer中绘制,以便背景仍然可见。
我不想为每张图片使用CALayer,最终会有20 000个CALayer或更多......
那么如何在CALayer中整理图像的“图像”? (然后用作子图层)
代码示例:
// rootView which is a UIViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_sproutLayer = [[CGSproutLayer alloc] initWithLayer:[CALayer layer]];
[self.view.layer addSublayer:_sproutLayer];
[_sproutLayer setZPosition:1];
[_sproutLayer setNeedsDisplay];
_backgroundLayer = [[CALayer alloc] init];
CGRect positionOne = CGRectMake(100, 100, 150, 150);
_backgroundLayer.frame = positionOne;
_backgroundLayer.backgroundColor = [UIColor blueColor].CGColor;
_backgroundLayer.name = @"One";
_backgroundLayer.contents = (id) [UIImage imageNamed:@"background.png"].CGImage;
[self.view.layer addSublayer:_backgroundLayer];
[_backgroundLayer setZPosition:0];
[_backgroundLayer setNeedsDisplay];
_refreshTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(doIterate:) userInfo:nil repeats:YES];
}
- (void)doIterate:(NSTimer *)timer
{
[self.something doComputeStuff];
...
[_sproutLayer draw];
}
// CGSproutLayer which is a CALAyer
- (void)draw
{
int cellSize = self.bounds.size.width / WIDTH;
double xOffset = 0;
CGRect cellFrame = CGRectMake(0, 0, cellSize, cellSize);
NSUInteger cellIndex = 0;
cellFrame.origin.x = xOffset;
for (int i = 0; i < WIDTH; i++)
{
cellFrame.origin.y = 0;
for (int j = 0; j < HEIGHT; j++, cellIndex++)
{
NSNumber *currentCell = [self.levelState.board objectAtIndex:cellIndex];
if (currentCell.intValue == sprouts)
{
[image1 drawInRect:cellFrame];
}
else if (currentCell.intValue == grass)
{
[image2 drawInRect:cellFrame];
}
cellFrame.origin.y += cellSize;
}
cellFrame.origin.x += cellSize;
}
}
答案 0 :(得分:1)
我解决了它,就像sethHB建议的那样: 这个解决方案非常快,足以满足我上面建议的图像数量。
- (void)draw
{
CGSize size = self.view.frame.size;
UIGraphicsBeginImageContext(size);
CGRect cellFrame = CGRectMake(0, 0, cellSize, cellSize);
for (int i = 0; i < WIDTH; i++)
{
cellFrame.origin.y = 0;
for (int j = 0; j < HEIGHT; j++, cellIndex++)
{
CGPoint pp = CGPointMake(i, j);
if (currentCell.intValue == sprouts)
{
[image1 drawAtPoint:pp blendMode:kCGBlendModeOverlay alpha:1.0];
}
else if (currentCell.intValue == grass)
{
[image2 drawAtPoint:pp blendMode:kCGBlendModeOverlay alpha:1.0];
}
}
cellFrame.origin.y += cellSize;
}
cellFrame.origin.x += cellSize;
}
UIImage* blendedImage = UIGraphicsGetImageFromCurrentImageContext();
_frontLayer.contents = (id) blendedImage.CGImage;
UIGraphicsEndImageContext();
}
谢谢SethHB!