iOS - 在子视图中绘制Bezier路径

时间:2015-07-30 16:11:18

标签: ios objective-c core-graphics

我正在学习CoreGraphic,想要制作一个简单的游戏,但是坚持用bezier路径绘制东西,我想在子视图中绘制一个三角形,但它总是出错,我希望它适合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];

看起来像这样: enter image description here

1 个答案:

答案 0 :(得分:2)

如果尺寸不正确,您可能在AutoLayout完成其工作之前创建了三角形。

为确保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 可能被多次调用。

-g