gpt4 book ai didi

ios - 如何同时绘制到多个 CGLayer?

转载 作者:可可西里 更新时间:2023-11-01 06:14:49 24 4
gpt4 key购买 nike

我想从同一个 for 循环中将对象绘制到两个单独的 CGLayer,但不确定如何执行此操作。

例如,我想在三个蓝色圆圈后面画三个橙色圆圈,橙色圆圈在一层,蓝色圆圈在另一层。以下代码会将每个圆圈放在前一个圆圈的顶部:

-(void) drawRect:(CGRect)rect {
UIBezierPath *circle;
for (int i = 1; i <= 3; i++) {
// Create an orange circle
circle = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(CGRectMake(i*50, 80, 50, 50), 0, 0)];
circle.lineWidth = 4.0f;
[[UIColor colorWithRed:1.0 green:0.75 blue:0 alpha:1.0] setFill];
[[UIColor orangeColor] setStroke];
[circle stroke];
[circle fill];

// Create a blue circle
circle = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(CGRectMake(25 + i*50, 80, 50, 50), 0, 0)];
circle.lineWidth = 4.0f;
[[UIColor colorWithRed:0 green:0.5 blue:1.0 alpha:1.0] setFill];
[[UIColor blueColor] setStroke];
[circle stroke];
[circle fill];
}
}

Output from the code above

我该如何修改它,使三个橙色圆圈最终位于 orangeLayer 中,而该 orangeLayer 位于 blueLayer 中三个蓝色圆圈的后面?我想这与保存和恢复上下文有关,但我无法真正理解它。

非常感谢!

PS:我意识到我可以简单地使用两个 for 内联循环来实现正确的效果,但是这个例子是为了学习分层的教学目的。谢谢!

最佳答案

我构建了 UIView 的自定义子类,并创建了一个函数 makeCircleWithFrame 以使用 UIGraphicsBeginImageContextWithOptions 在 View 内绘制一个圆圈,我相信它会解决您的主要问题:

#import "circleView.h"
#import <math.h>

@implementation circleView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (!self) return self;

[self setupViews];

return self;
}

- (void)awakeFromNib
{
[self setupViews];
}

- (void)setupViews
{
[self setBackgroundColor:[UIColor whiteColor]];


for (int i = 1; i <= 6; i++) {

UIColor *circleColor;

//Math function just to set different colors for each circle
if (fmodf(i, 2) == 0) {
circleColor = [UIColor colorWithRed:1.0 green:0.75 blue:0 alpha:1.0];
}
else {
circleColor = [UIColor colorWithRed:0 green:0.5 blue:1.0 alpha:1.0];
}


UIView *circleView = [self makeCircleWithFrame:(CGRectMake(10*i, 10*i, 100, 100)) andFillColor:circleColor];
circleView.tag = i;
NSLog(@"circle %i", i);
}
}

- (UIView *)makeCircleWithFrame:(CGRect)rect andFillColor:(UIColor *)color {
// declare UIimageView, not UIView
UIImageView *customView = [[UIImageView alloc] init];
customView.frame= self.bounds;

// create a new contex to draw
UIGraphicsBeginImageContextWithOptions(CGSizeMake(200, 200), NO, 0);

UIBezierPath *grayCircle = [UIBezierPath bezierPathWithOvalInRect:rect];

grayCircle.lineWidth = 6;
[color setFill];
[[UIColor orangeColor] setStroke];
[grayCircle stroke];
[grayCircle fill];

customView.image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

[self addSubview:customView];

return customView;
}

如果您仍有问题或需要帮助,请给我反馈。

关于ios - 如何同时绘制到多个 CGLayer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26394939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com