CAShapeLayers没有绘制自定义子类(UIControl)

时间:2014-11-04 09:36:08

标签: ios objective-c uitableview calayer cashapelayer

在尝试在自定义UIControl子类中绘制几个CAShapeLayer时,我遇到了一个奇怪的问题。我确信它是显而易见的,但是24小时后,我无法使它发挥作用。

我这样做:

// .h
@interface IntercomButton : UIControl

@end

// .m
@interface IntercomButton()
@property (nonatomic) CAShapeLayer *outerCircle, *innerCircle;
@end

@implementation IntercomButton

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _innerCircle = [CAShapeLayer layer];
        _outerCircle = [CAShapeLayer layer];

        _innerCircle.frame = frame;
        _outerCircle.frame = frame;

        [self.layer addSublayer:_innerCircle];
        [self.layer addSublayer:_outerCircle];
    }
    return self;
}

- (void)layoutSubviews {

    _innerCircle.frame = self.frame;
    _innerCircle.strokeColor = NULL;
    _innerCircle.fillColor = [UIColor colorWithRed:0.377 green:0.664 blue:0.894 alpha:1.000].CGColor;
    _innerCircle.path = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(self.frame, 12, 12)].CGPath;
    //_innerCircle.rasterizationScale = 2.0 * [UIScreen mainScreen].scale;
    //_innerCircle.shouldRasterize = YES;
    //[self.layer addSublayer:_innerCircle];

    _outerCircle.frame = self.frame;
    _outerCircle.lineWidth = 4.0f;
    _outerCircle.strokeColor = [UIColor colorWithRed:0.377 green:0.664 blue:0.894 alpha:1.000].CGColor;
    _outerCircle.fillColor = NULL;
    _outerCircle.path = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(self.frame, 6, 6)].CGPath;
    //_outerCircle.rasterizationScale = 2.0 * [UIScreen mainScreen].scale;
    //_outerCircle.shouldRasterize = YES;
    //[self.layer addSublayer:_outerCircle];
}

@end

它是在另一个视图中创建的视图(它在UITableViewCell中,而不是我觉得它很重要,但仍然......)

IntercomButton *intercomButton = [[IntercomButton alloc] initWithFrame:btn.frame];
intercomButton.backgroundColor = [UIColor clearColor];
[detailView addSubview:intercomButton];

UIControl视图正好被添加,因为如果我更改背景颜色,它会显示。

另外,如果我使用drawRect绘制,它可以工作:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0.377 green:0.664 blue:0.894 alpha:1.000].CGColor);
    CGContextFillEllipseInRect (context, CGRectInset(rect, 12, 12));
    CGContextFillPath(context);

    CGContextSetLineWidth(context, 3.0f);
    CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.377 green:0.664 blue:0.894 alpha:1.000].CGColor);
    CGContextStrokeEllipseInRect(context, CGRectInset(rect, 8, 8));
    CGContextStrokePath(context);
}

问题是我需要为它设置动画,所以我需要使用CAShapeLayers。 我想要绘制的内容应该是这样的(这是使用drawRect看起来的样子:)

enter image description here

1 个答案:

答案 0 :(得分:0)

好吧,我会被诅咒,问题在于做什么

CGRectInset(self.frame, X, X)

我应该做什么

CGRectInset(self.bounds, X, X)

所以层位于视图框外的位置。

正如我所说,它结束了显而易见的事情。