Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centre Align CAShape layer in a UIView

The following is a image for which the the code does not align the centre of the UIView , white color.

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];

enter image description here

like image 734
NNikN Avatar asked Jun 04 '16 01:06

NNikN


1 Answers

anchorPoint is not for setting the position of CAShapeLayer, use position instead.

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)

Edit

Sorry for such a rough answer before, the code above may not work as you want, here is the correct answer I just come out. A important thing to note is: How you draw the oval path did effect the position of your 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

From Apple Document,

The oval path is created in a clockwise direction (relative to the default coordinate system)

In other word, the oval path is drawn from the edge instead of the center, so you must take into accound the radius of the oval you are drawing. In your case, you need to do this:

layer.path = UIBezierPath(ovalInRect: CGRectMake(-75.0 / 2, -75.0 / 2, 75.0, 75.0)).CGPath 

Now we ensure that the center of drawn path is equal to the center of CAShapeLayer. Then we can use position property to move the CAShapeLayer as we want. The image below could help you understand.

enter image description here enter image description here

like image 52
ilovecomputer Avatar answered Nov 11 '22 10:11

ilovecomputer