簡體   English   中英

iOS-在子視圖中繪制Bezier路徑

[英]iOS - Draw Bezier Path in Subview

我正在學習CoreGraphic並想做一個簡單的游戲,但是想用貝塞爾曲線畫圖,我想在子視圖中畫一個三角形,但它總是出錯,我希望它適合正方形視圖的1/4。

我的代碼:

UIBezierPath* trianglePath = [UIBezierPath bezierPath];
[trianglePath moveToPoint:CGPointMake(0, 0)];
[trianglePath addLineToPoint:CGPointMake(self.mainView.frame.size.width/2, self.mainView.frame.size.height/2)];
[trianglePath addLineToPoint:CGPointMake(self.mainView.frame.size.width, 0)];
[trianglePath closePath];

CAShapeLayer *triangleMaskLayer = [CAShapeLayer layer];
[triangleMaskLayer setPath:trianglePath.CGPath];

UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0,0, self.mainView.frame.size.width, self.mainView.frame.size.height)];

firstView.backgroundColor = [UIColor colorWithWhite:.75 alpha:1];
firstView.layer.mask = triangleMaskLayer;
[self.mainView addSubview:firstView];

看起來像這樣: 在此處輸入圖片說明

如果尺寸不正確,則可能是在AutoLayout完成其工作之前創建了三角形。

為確保self.mainView的大小正確,請在控制器的viewDidLayoutSubviews方法中創建三角形。

另外請注意, viewDidLayoutSubviews可能會多次調用。

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void) viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    if (self.mainView.subviews.count == 0) {
        UIBezierPath* trianglePath = [UIBezierPath bezierPath];
        [trianglePath moveToPoint:CGPointMake(0, 0)];
        [trianglePath addLineToPoint:CGPointMake(self.mainView.frame.size.width/2, self.mainView.frame.size.height/2)];
        [trianglePath addLineToPoint:CGPointMake(self.mainView.frame.size.width, 0)];
        [trianglePath closePath];

        CAShapeLayer *triangleMaskLayer = [CAShapeLayer layer];
        [triangleMaskLayer setPath:trianglePath.CGPath];

        UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0,0, self.mainView.frame.size.width, self.mainView.frame.size.height)];

        firstView.backgroundColor = [UIColor colorWithWhite:.75 alpha:1];
        firstView.layer.mask = triangleMaskLayer;
        [self.mainView addSubview:firstView];

    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM