我是使用UIBezierPaths绘制形状的新手。到目前为止,我发现的所有示例都涉及首先对视图进行子类化,然后重写drawRect:
方法并在那里进行绘制,但我还没有找到任何可以绝对肯定地说明这是否是是在UIView中绘制UIBezierPaths的唯一方法,或者这只是最实用的方式。
还有其他方法(除了调配)在UIView中绘制UIBezierPath而不进行子类化吗?
答案 0 :(得分:15)
在不使用drawRect的情况下绘制贝塞尔路径的另一种方法是使用CAShapeLayers。将形状图层的path属性设置为从bezier路径创建的CGPath。将形状图层添加为视图图层的子图层。
UIBezierPath *shape = [UIBezierPath bezierPathWithOvalInRect:self.view.bounds];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = shape.CGPath;
shapeLayer.fillColor = [UIColor colorWithRed:.5 green:1 blue:.5 alpha:1].CGColor;
shapeLayer.strokeColor = [UIColor blackColor].CGColor;
shapeLayer.lineWidth = 2;
[self.view.layer addSublayer:shapeLayer];
答案 1 :(得分:6)
接受答案的Swift版本:
let shape = UIBezierPath(ovalInRect: view.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = shape.CGPath
shapeLayer.fillColor = UIColor(red: 0.5, green: 1, blue: 0.5, alpha: 1).CGColor
shapeLayer.strokeColor = UIColor.blackColor().CGColor
shapeLayer.lineWidth = 2.0
view.layer.addSublayer(shapeLayer)
答案 2 :(得分:0)
您可以:1)将UIBezierPaths渲染到图像上下文中。 2)添加UIImageView作为视图的子视图,并使用渲染图像设置图像属性。 像这样:
- (void)viewDidLoad {
[super viewDidLoad];
self.imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.imageView];
[self drawPaths];
}
- (void)drawPaths {
UIGraphicsBeginImageContext(self.view.bounds);
//draw...
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
答案 3 :(得分:0)
let shape = UIBezierPath(ovalIn: view.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = shape.cgPath
shapeLayer.fillColor = UIColor(red: 0.5, green: 1, blue: 0.5, alpha: 1).cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 2.0
view.layer.addSublayer(shapeLayer)