2011-03-25 36 views
6

我試了幾個小時,用CAShapeLayer在我的UIView周圍得到了一個虛線的邊框,但是我沒有看到它。
ScaleOverlay.h在UIView子類中使用的CAShapeLayer不起作用

#import <UIKit/UIKit.h> 
#import <QuartzCore/QuartzCore.h> 

@interface ScaleOverlay : UIView <UIGestureRecognizerDelegate> { 
    CAShapeLayer *shapeLayer_; 
} 
@end 

ScaleOverlay.m

- (id)initWithFrame:(CGRect)frame 
{ 
self = [super initWithFrame:frame]; 
if (self) { 
    self.backgroundColor = [UIColor redColor]; 
    self.alpha = 0; 
    //Round corners 
    [[self layer] setCornerRadius:8.f]; 
    [[self layer] setMasksToBounds:YES]; 
    //Border 
    shapeLayer_ = [[CAShapeLayer layer] retain]; 

    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathAddRect(path, NULL, frame); 
    shapeLayer_.path = path; 
    CGPathRelease(path); 
    shapeLayer_.backgroundColor = [[UIColor clearColor] CGColor]; 
    shapeLayer_.frame = frame; 
    shapeLayer_.position = self.center; 

    [shapeLayer_ setValue:[NSNumber numberWithBool:NO] forKey:@"isCircle"]; 
    shapeLayer_.fillColor = [[UIColor blueColor] CGColor]; 
    shapeLayer_.strokeColor = [[UIColor blackColor] CGColor]; 
    shapeLayer_.lineWidth = 4.; 
    shapeLayer_.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:8], [NSNumber numberWithInt:8], nil]; 
    shapeLayer_.lineCap = kCALineCapRound; 
} 
return self; 
} 

我在我的上海華繪製的紅色矩形,但沒有邊界。從一個源代碼複製這個例子,希望它可以工作,但事實並非如此。

回答

16

你永遠不會添加shapeLayer作爲你的UIView圖層的子圖層,所以它永遠不會顯示在屏幕上。嘗試添加

[self.layer addSublayer:shapeLayer_]; 

在您的-initWithFrame:方法中設置了CAShapeLayer後。

更妙的是,你可以嘗試通過覆蓋下面的類方法使你的UIView的襯底層CAShapeLayer:

+ (Class) layerClass 
{ 
    return [CAShapeLayer class]; 
} 

然後,您可以與視圖的層直接處理,並消除額外CAShapeLayer實例變量。

+0

不能相信我忘了'[self.layer addSublayer:shapeLayer _];'並且搜索到天數 – Seega 2011-03-28 07:22:55

+1

由於某種原因,您不能使用CAShapeLayer作爲背景層。 – openfrog 2013-05-01 20:34:38

+0

@openfrog我看到了完全相同的行爲。很奇怪... – LucasTizma 2017-03-18 22:01:21