Search code examples
swiftcore-graphicscalayercashapelayer

Center CAShapeLayer


I Have tried to Center CAShapeLayer in UIImageView but didn't succeed and I have find solution that I have added it(CAShapeLayer) to UIVIew and then Add UIVIew to ImageView and its worked !!!

Is this good practices ? any suggestion

func Draw(Fn:Bool) {

        let theCenter = CGPoint(x: img.bounds.midX, y: img.bounds.midY)

        // Create Layer To Add The CAShapeLayer On it So I can Center it
        let DrawingLayer = UIView(frame: CGRect(x: img.bounds.midX, y: img.bounds.midY, width: 140, height: 80))
        DrawingLayer.center = theCenter
        img.addSubview(DrawingLayer)

        // Create The Drawing
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 140, height: 80)).cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor

        shapeLayer.lineWidth = 3.0


        // Add Drawing to UIView
        DrawingLayer.layer.addSublayer(shapeLayer)
        // Add UIView To ImageView
        img.addSubview(DrawingLayer)
    }

I was using this code :

func DrawArmor(Fn:Bool) {

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 140, height: 80)).cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor

        shapeLayer.lineWidth = 3.0
        if (Fn) {
            shapeLayer.name = "Armor Friendly"
            shapeLayer.strokeColor = UIColor.blue.cgColor
        }else{
            shapeLayer.name = "ArmorEnemy"
            shapeLayer.strokeColor = UIColor.red.cgColor
        }

        img.layer.addSublayer(shapeLayer)
    }

but the Drawing showing on right bottom corner which mean the ancherpoint is not the center

enter image description here


Solution

  • Find a solution

    shapeLayer.frame = CGRect(x: img.bounds.midX, y: img.bounds.midY, width: 140, height: 80)
    shapeLayer.position = CGPoint(x: img.bounds.midX, y: img.bounds.midY)
    

    I have set a size of the CAShapeLayer and then set the position for it and its work