Swift:如何锚定图层进行查看?

时间:2016-10-06 05:21:59

标签: swift uiview position cashapelayer anchorpoint

我一直在尝试将CAShapeLayer锚定到视图中几天。我找不到解决方案。这是一个facetracker项目。我想创建一个圆形的CAShapeLayer,我可以放在eyeglassesView中的固定位置。但是,当您转过头时视图会调整大小,因此CAShapeLayer无法保持在眼镜顶部作为镜头。我打算制作一些动画,但是我需要CAShapeLayer首先坚持它的位置,无论我移动到哪个角度。

func faceTrackerDidUpdate(points: FacePoints?) {
    let eyeCornerDist = sqrt(pow(points.leftEye[0].x - points.rightEye[5].x, 2) + pow(points.leftEye[0].y - points.rightEye[5].y, 2))
    let eyeToEyeCenter = CGPointMake((points.leftEye[0].x + points.rightEye[5].x) / 2, (points.leftEye[0].y + points.rightEye[5].y) / 2)

    let eyeglassesWidth = 1.5 * eyeCornerDist
    let eyeglassesHeight = (eyeglassesView.image!.size.height / eyeglassesView.image!.size.width) * eyeglassesWidth

    eyeglassesView.transform = CGAffineTransformIdentity

    eyeglassesView.frame = CGRectMake(eyeToEyeCenter.x - eyeglassesWidth / 2, eyeToEyeCenter.y - 0.5 * eyeglassesHeight, eyeglassesWidth, eyeglassesHeight)

    let layer = CAShapeLayer()
    layer.anchorPoint = CGPointMake(0.0, 1.0)
    layer.position = CGPointMake(0.0, 150.0)
    layer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 80, height: 80), cornerRadius: 80).CGPath
    layer.fillColor = UIColor(white: 1, alpha: 0.08).CGColor

    eyeglassesView.layer.addSublayer(layer)

    eyeglassesView.hidden = false

    setAnchorPoint(CGPointMake(0.5, 1.0), forView: eyeglassesView)

    let angle = atan2(points.rightEye[5].y - points.leftEye[0].y, points.rightEye[5].x - points.leftEye[0].x)
    eyeglassesView.transform = CGAffineTransformMakeRotation(angle)
}

func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
    var newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x, view.bounds.size.height * anchorPoint.y)
    var oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x, view.bounds.size.height * view.layer.anchorPoint.y)

    newPoint = CGPointApplyAffineTransform(newPoint, view.transform)
    oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform)

    var position = view.layer.position
    position.x -= oldPoint.x
    position.x += newPoint.x

    position.y -= oldPoint.y
    position.y += newPoint.y

    view.layer.position = position
    view.layer.anchorPoint = anchorPoint
}

我尝试了不同的东西,位置,锚点,masktobounds,转换,但我真的不知道如何让它工作。任何帮助将不胜感激。如果我有什么遗漏,请告诉我。

0 个答案:

没有答案