在视图中重新定位CGPath/UIBezierPath

Lit*_*Dev 9 cgpath ios uibezierpath

是否可以在视图上重新定位已绘制的CGPath/UIBezierPath?我想移动或改变路径的位置然后可能回想起drawinRect方法再次显示图形.

Dav*_*ist 20

从你的问题来看,听起来你正在使用Core Graphics绘制路径drawRect:(与使用a相比CAShapeLayer)所以我将首先解释该版本.

移动CGPath

您可以通过转换另一个路径来创建新路径.平移变换将变换后的对象在x和y中移动一定距离.因此,使用平移变换,您可以在x和y中移动现有路径一定数量的点.

CGAffineTransform translation = CGAffineTransformMakeTranslation(xPixelsToMove,
                                                                 yPixelsToMove);
CGPathRef movedPath = CGPathCreateCopyByTransformingPath(originalCGPath,
                                                         &translation);
Run Code Online (Sandbox Code Playgroud)

然后你可以使用movedPath与你已经做的相同的方式绘制.

您也可以更改修改相同的路径

yourPath = CGPathCreateCopyByTransformingPath(yourPath,
                                              &translation);
Run Code Online (Sandbox Code Playgroud)

并简单地重绘它.

移动形状图层

如果您使用的是形状图层,移动它会更容易.然后,您只需使用position属性更改图层的位置.

更新:

如果要使用形状图层,只需创建一个新的CAShapeLayer并将其路径设置为您的CGPath.由于CAShapeLayer是Core Animation的一部分,因此您需要QuartzCore.framework.

CAShapeLayer *shape = [CAShapeLayer layer];
shape.path = yourCGParth;
shape.fillColor = [UIColor redColor].CGColor;

[someView.layer addSublayer:shape];
Run Code Online (Sandbox Code Playgroud)

然后移动形状你只需改变它的位置.

shape.position = thePointYouWantToMoveTheShapeTo;
Run Code Online (Sandbox Code Playgroud)


小智 5

/// 将 cgPath 从其中心平移到指定点。无需移动形状图层。移动路径将使应用程序平滑

func translate(path : CGPath?, by point: CGPoint) -> CGPath? {

    let bezeirPath = UIBezierPath()
    guard let prevPath = path else {
        return nil
    }
    bezeirPath.cgPath = prevPath
    bezeirPath.apply(CGAffineTransform(translationX: point.x, y: point.y))

    return bezeirPath.cgPath
}
Run Code Online (Sandbox Code Playgroud)