Reposition CGPath/UIBezierPath in View

让人想犯罪 __ 提交于 2019-12-03 09:43:11

问题


Is it possible to reposition an already drawn CGPath/UIBezierPath on a view? I would like to move or change a path's position then perhaps recall the drawinRect method to just show the drawing again.


回答1:


From your question it sounds like you are drawing the path using Core Graphics inside drawRect: (as compared to using a CAShapeLayer) so I'll explain the version first.

Moving a CGPath

You can create a new path by transforming another path. A translation transform moves the transformed object a certain distance in x and y. So using a translation transform you can move your existing path a certain number of points in both x and y.

CGAffineTransform translation = CGAffineTransformMakeTranslation(xPixelsToMove,
                                                                 yPixelsToMove);
CGPathRef movedPath = CGPathCreateCopyByTransformingPath(originalCGPath,
                                                         &translation);

Then you could use the movedPath to draw the same way you are already doing.

You could also change modify the same path

yourPath = CGPathCreateCopyByTransformingPath(yourPath,
                                              &translation);

and simply redraw it.

Moving a shape layer

If you are using a shape layer, moving it is even easier. Then you only have to change the position of the layer using the position property.

Update:

If you want to use a shape layer you can simply create a new CAShapeLayer and set its path to be your CGPath. You will need QuartzCore.framework for this since CAShapeLayer is part of Core Animation.

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

[someView.layer addSublayer:shape];

Then to move the shape you simply change its position.

shape.position = thePointYouWantToMoveTheShapeTo;



回答2:


/// Provide cgpath to it and tanslate it by given point.

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
}



回答3:


/// Translate cgPath from its center to give point.No need to move shape layer .Moving path will make app smooth

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
}


来源:https://stackoverflow.com/questions/17168931/reposition-cgpath-uibezierpath-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!