以下是代码未对齐UIView中心的图像,白色.
CAShapeLayer *layer = [CAShapeLayer layer];
layer.anchorPoint=CGPointMake(0.5, 0.5);
layer.path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 75.0, 75.0)].CGPath;
layer.fillColor =[UIColor redColor].CGColor;
[self.shapeView.layer addSublayer:layer];
Run Code Online (Sandbox Code Playgroud)
bil*_*p22 10
anchorPoint不是用于设置CAShapeLayer的位置,而是使用position.
let layer = CAShapeLayer()
layer.borderColor = UIColor.blackColor().CGColor
layer.borderWidth = 100
layer.bounds = CGRectMake(0, 0, 50, 50)
layer.position = myView.center
layer.fillColor = UIColor.redColor().CGColor
view.layer.addSublayer(layer)
Run Code Online (Sandbox Code Playgroud)
编辑
对不起,以前这么粗略的回答,上面的代码可能无法正常工作,这是我刚出来的正确答案.需要注意的一件重要事情是:如何绘制椭圆形路径确实影响了你的位置CAShapeLayer
let layer = CAShapeLayer()
myView.layer.addSublayer(layer)
layer.fillColor = UIColor.redColor().CGColor
layer.anchorPoint = CGPointMake(0.5, 0.5)
layer.position = CGPointMake(myView.layer.bounds.midX, myView.layer.bounds.midY)
layer.path = UIBezierPath(ovalInRect: CGRectMake(-75.0 / 2, -75.0 / 2, 75.0, 75.0)).CGPath
Run Code Online (Sandbox Code Playgroud)
来自Apple Document,
椭圆形路径以顺时针方向创建(相对于默认坐标系)
换句话说,椭圆形路径是从边缘而不是中心绘制的,因此您必须考虑正在绘制的椭圆的半径.在您的情况下,您需要这样做:
layer.path = UIBezierPath(ovalInRect: CGRectMake(-75.0 / 2, -75.0 / 2, 75.0, 75.0)).CGPath
Run Code Online (Sandbox Code Playgroud)
现在我们确保绘制路径的中心等于中心CAShapeLayer.然后我们可以使用position属性来移动CAShapeLayer我们想要的.下面的图片可以帮助您理解.