我正在学习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];

看起来像这样:
ios - iOS-在 subview 中绘制Bezier路径-LMLPHP

最佳答案

如果尺寸不正确,则可能是在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

关于ios - iOS-在 subview 中绘制Bezier路径,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31728924/

10-09 14:34