2014-11-04 92 views
0

我在嘗試在自定義UIControl子類中繪製幾個CAShapeLayer時出現了一個奇怪的問題。我相信這是顯而易見的,但在24小時後,我無法完成工作。CAShapeLayers不繪製自定義子類(UIControl)

我做這樣的:

// .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

回答

0

好吧,我真該死,問題是用做

CGRectInset(self.frame, X, X) 

當我應該已經做

CGRectInset(self.bounds, X, X) 

那麼,得到位於該視圖幀以外THA層。

正如我所說,它結束了一些明顯的事情。