2014-10-07 36 views
0

我試圖找到實現圓角矩形的最佳方式(例如像iphone圖標一樣的looling)。我的搜索建議使用UIBezierPath。如何使用UIBezierPath修復無效的上下文0x0?

爲了測試類我做了一個新的Xcode模板(單一視圖應用),基本上只是加入的ViewController的viewDidLoad以下行:

UIBezierPath* path = [UIBezierPath 
         bezierPathWithRoundedRect: CGRectMake(10, 10, 120, 120) 
         cornerRadius: 5]; 
[[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0] setFill]; 
[path stroke]; 
[path fill]; 

現在,我得到幾個」 ......無效的上下文爲0x0錯誤...」。我認爲我必須先設置一個上下文?!但是,我該如何做,或者如果不能解決這些錯誤呢?

我對這個錯誤的搜索有幾個帖子。不幸的是,他們所有人似乎都有相當複雜的編碼。但我很確定,我在這裏只是有一個非常基本的誤解。

謝謝!

+0

我建議閱讀[石英2D編程指南(https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/Introduction/Introduction.html#//apple_ref/doc/uid/ TP30001066)。 – Desdenova 2014-10-07 12:09:14

+0

@Desdenova謝謝!這看起來不錯 - 我會檢查它。 – McMini 2014-10-07 12:15:29

回答

2

,你可以用這個和分配,在你的情況下,鑑於

UIBezierPath *maskpath=[UIBezierPath bezierPathWithRoundedRect:view1.bounds 
    byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight 
    cornerRadii:CGSizeMake(10.0,10.0)]; 

    CAShapeLayer *maskLayer=[CAShapeLayer layer]; 

    maskLayer.frame=view1.bounds; 

    maskLayer.path=maskpath.CGPath; 

    [view1.layer addSublayer:maskLayer]; 
+0

這是非常誤導。你不需要屏蔽一個圖層來繪製帶有圓角的'CAShapeLayer'。 – Desdenova 2014-10-07 12:03:57

+0

感謝您的快速回答!顯然這個問題比我希望的更困難 - 我會嘗試理解你的代碼並回報... – McMini 2014-10-07 12:06:39

+0

@Desdenova那麼我們如何能讓視圖像圓角? – 2014-10-07 12:20:06

0

層是對別人有幫助的:由johnykumar提供的代碼和類似的話題另一篇文章的基礎:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.view.backgroundColor = [UIColor blackColor]; 
    CGRect frame = CGRectMake(50.0, 50.0, 150.0, 150.0); 
    CGFloat radius = 20.0; 
    UIView *frontView = [[UIView alloc] initWithFrame:frame]; 
    frontView.backgroundColor = [UIColor redColor]; 
    CAShapeLayer * maskLayer = [CAShapeLayer layer]; 
    maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:frontView.bounds 
              byRoundingCorners:UIRectCornerAllCorners 
               cornerRadii:CGSizeMake(radius,  radius)].CGPath; 
    frontView.layer.mask = maskLayer; 
    [self.view addSubview:frontView]; 
} 
相關問題