Objective c 如何在UIButton的子层上绘制?
我试图使用CoreGraphics和CALayers在UIButton上绘制一些奇特的图形,但我无法在子层上显示任何东西 下面是我如何设置我的子层:Objective c 如何在UIButton的子层上绘制?,objective-c,ios,uibutton,core-animation,quartz-graphics,Objective C,Ios,Uibutton,Core Animation,Quartz Graphics,我试图使用CoreGraphics和CALayers在UIButton上绘制一些奇特的图形,但我无法在子层上显示任何东西 下面是我如何设置我的子层: - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { // Initialization code CALayer *buttonLayer = self.layer;
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// Initialization code
CALayer *buttonLayer = self.layer;
buttonLayer.masksToBounds = YES;
buttonLayer.backgroundColor = [[UIColor clearColor] CGColor];
self.myDelegate = [[PlayerButtonLayerDelegate alloc] init];
CALayer *customDrawn = [CALayer layer];
customDrawn.delegate = self.myDelegate;
customDrawn.frame = buttonLayer.frame;
customDrawn.masksToBounds = YES;
[buttonLayer insertSublayer:customDrawn atIndex:0];
[customDrawn setNeedsDisplay];
}
return self;
}
PlayerButtonLayerDelegate只实现了drawLayer:inContext:
如下:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context {
CGRect rectangleFrame = layer.bounds;
UIGraphicsPushContext(context);
UIBezierPath* rectanglePath =
[UIBezierPath bezierPathWithRect: rectangleFrame];
[[UIColor redColor] setFill];
[rectanglePath fill];
UIGraphicsPopContext();
}
代码被调用(我可以设置一个断点或输出到NSLog),但没有显示任何内容:我只有一个透明的按钮(如主层所示),有或没有任何按钮文本
在子层上“绘制”需要更改什么?您应该将子层的
帧设置为按钮层的边界,而不是其帧。但不确定这是否是唯一的问题。Doh.:-)你能把这个作为答案提交给我吗?这样我就可以+1/接受它了?一旦有人指出,这是显而易见的!如果还有其他问题,请告诉我!谢谢。您应该将子层的帧
设置为按钮层的边界
,而不是其帧。但不确定这是否是唯一的问题。Doh.:-)你能把这个作为答案提交给我吗?这样我就可以+1/接受它了?一旦有人指出,这是显而易见的!如果还有其他问题,请告诉我!谢谢
[customDrawn setFrame:buttonLayer.bounds];