1.i创建了CAshapelayer,并在CAshapelayer中成功插入了一个标签,但是现在我试图在图层中设置图像,但是它不起作用。
CAShapeLayer *circleLayer = [CAShapeLayer layer];
[circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 250, 100, 100)] CGPath]];
circleLayer.contents = (id)[[UIImage imageNamed:@"001-forward.png"] CGImage];
circleLayer.contentsGravity=kCAGravityResize;
// circleLayer.masksToBounds = YES;
[circleLayer setStrokeColor:[[UIColor brownColor] CGColor]];
[circleLayer setFillColor:[[UIColor clearColor] CGColor]];
[[self.view layer] addSublayer:circleLayer];
CATextLayer *label = [[CATextLayer alloc] init];
[label setFont:@"Helvetica-Bold"];
[label setFontSize:15];
[label setFrame:CGRectMake(50,300, 100, 50)];
[label setString:@"GM"];
[label setAlignmentMode:kCAAlignmentCenter];
[label setForegroundColor:[[UIColor greenColor] CGColor]];
[circleLayer addSublayer:label];
最佳答案
这里的主要问题是您不能将UIImage
作为CAShape Layer
的内容添加,因为您可以在此处看到UIImage as CAShapeLayer contents,所以我已经修改了代码,将Image添加到CALayer
并将该层添加到circleLayer
CGRect frame = CGRectMake(50, 250, 100, 100);
// Do any additional setup after loading the view, typically from a nib.
CAShapeLayer *circleLayer = [CAShapeLayer layer];
[circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:frame] CGPath]];
circleLayer.contentsGravity=kCAGravityResize;
// circleLayer.masksToBounds = YES;
[circleLayer setStrokeColor:[[UIColor brownColor] CGColor]];
//[circleLayer setFillColor:[[UIColor clearColor] CGColor]];
[[self.view layer] addSublayer:circleLayer];
CATextLayer *label = [[CATextLayer alloc] init];
[label setFont:@"Helvetica-Bold"];
[label setFontSize:15];
[label setFrame:CGRectMake(50,300, 100, 50)];
[label setString:@"GM"];
[label setAlignmentMode:kCAAlignmentCenter];
[label setForegroundColor:[[UIColor greenColor] CGColor]];
CALayer * imageLayer = [CALayer layer];
[imageLayer setContents: (__bridge id _Nullable)([[UIImage imageNamed:@"test"] CGImage])];
imageLayer.frame = frame; // Define a frame
imageLayer.contentsGravity=kCAGravityResize;
CAShapeLayer *maskLayer = [CAShapeLayer layer];
[maskLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, frame.size.width, frame.size.height)] CGPath]];
imageLayer.mask = maskLayer;
[circleLayer addSublayer:imageLayer];
[circleLayer addSublayer:label];
关于ios - 无法设置cashapelayer的图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45901540/