在屏幕中央放置CAShapeLayer圆形

4

我现在正在通过CAShapeLayer绘制一个圆,现在我希望我的圆在屏幕中央居中显示。圆的中心点必须是视图的中心点。

这是我现在尝试做到这一点的方法:

- (void)_initCircle {
    [_circle removeFromSuperlayer];
    _circle = [CAShapeLayer layer];
    _radius = 100;

    // Create a circle
    _circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0 * _radius, 2.0 * _radius) cornerRadius:_radius].CGPath;

    // Center the shape in self.view
    _circle.position = CGPointMake(CGRectGetMidX(self.view.bounds) - _radius,
                                   CGRectGetMidY(self.view.bounds) - _radius);

    _circle.fillColor = [UIColor clearColor].CGColor;
    _circle.lineWidth = 5;

    // Add to parent layer
    [self.view.layer addSublayer:_circle];
}

截图清晰地表明圆形在中间并不完美,因为标签位于屏幕中央(Y轴中心点)。我认为蓝色和黑色的圆应该等于标签。
我看不到计算错误,有人能帮帮我吗?
编辑:
将范围更改为框架,并放开半径后,给出了这个结果:
2个回答

2

图层相对于它们的锚点定位,因此您可以尝试执行以下操作:

// Center the shape in self.view
_circle.position = self.view.center;
_circle.anchorPoint = CGPointMake(0.5, 0.5);

这给了我与第二个截图相同的结果。 - user1007522

0
import UIKit

 class DrawCircleView.UIView{

 init(frame:CGRect){
      super,init(frame:frame)
   //Initialization code
}
 init(coder aDecoder:NSCoder!){
     super.init(coder:aDecoder)
}
//Only override drawRect:if you perform custom drawing.
//An empty implementation adversely affects performance during animation.
override func drawRect(rect:CGRect)
{
//Drawing code

var context = UIGraphicsGetCurrentContext()

CGContextAddArc(context, 150,300,100,0,3.14*2,0)
//you can change (150/300/100),these arguments to point the position.
CGContextStrokePath(context)
}
}

这只是将其硬编码设置,因此在其他屏幕上可能无法正常工作? - user1007522

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接