将CGPath按比例缩放以适应UIVIew

13

我需要知道如何缩小或放大CGPath,使其适合UIView。

将背景颜色设置为黄色,以便清晰地查看视图。

self.frame = CGRectMake(0, 0, 181, 154);
self.backgroundColor = [UIColor yellowColor];

绘制CAShapeLayer

CAShapeLayer *shape = [CAShapeLayer layer];
shape.path = aPath;

shape.strokeColor = [[UIColor blueColor] CGColor];
shape.lineWidth = 5;
shape.fillColor = [[UIColor clearColor] CGColor];

[self.layer addSublayer:shape];

然后我得到了这个:

enter image description here

我想要的是这个:

enter image description here

谢谢开发者们 :)


你首先如何获取路径?根据路径的设置方式,可能只需要在形状图层上设置“frame”即可。 - DBD
@DBD 我使用了这个类,链接 - MAMN84
3个回答

35
我假设你想要完全填充(不变形)形状以适应视图。我还假设您已经有了具有路径的形状层,因为问题被标记为CAShapeLayer。
在这种情况下,您将获得形状图层路径的边界框,并计算适用于该路径的适当比例因子。
根据形状的纵横比和它应该适合的视图,宽度或高度将确定比例因子。
一旦您有了比例因子,就会创建一个变换来应用于路径。由于路径可能不从(0,0)开始,因此您还需要在变换中将路径平移(移动)到边界框原点。
如果您希望新路径位于视图中心,则需要计算要移动多少。如果您不需要,请注释掉该代码,但我也包含了它以供其他人阅读此答案时使用。
最后,您有一个新路径,所以您只需创建一个新形状层,分配路径,适当地设置样式并将其添加到视图中即可。
// I'm assuming that the view and original shape layer is already created
CGRect boundingBox = CGPathGetBoundingBox(shapeLayer.path);

CGFloat boundingBoxAspectRatio = CGRectGetWidth(boundingBox)/CGRectGetHeight(boundingBox);
CGFloat viewAspectRatio = CGRectGetWidth(viewToFitIn.frame)/CGRectGetHeight(viewToFitIn.frame);

CGFloat scaleFactor = 1.0;
if (boundingBoxAspectRatio > viewAspectRatio) {
    // Width is limiting factor
    scaleFactor = CGRectGetWidth(viewToFitIn.frame)/CGRectGetWidth(boundingBox);
} else {
    // Height is limiting factor
    scaleFactor = CGRectGetHeight(viewToFitIn.frame)/CGRectGetHeight(boundingBox);
}


// Scaling the path ...
CGAffineTransform scaleTransform = CGAffineTransformIdentity;
// Scale down the path first
scaleTransform = CGAffineTransformScale(scaleTransform, scaleFactor, scaleFactor);
// Then translate the path to the upper left corner
scaleTransform = CGAffineTransformTranslate(scaleTransform, -CGRectGetMinX(boundingBox), -CGRectGetMinY(boundingBox));

// If you want to be fancy you could also center the path in the view
// i.e. if you don't want it to stick to the top.
// It is done by calculating the heigth and width difference and translating
// half the scaled value of that in both x and y (the scaled side will be 0)
CGSize scaledSize = CGSizeApplyAffineTransform(boundingBox.size, CGAffineTransformMakeScale(scaleFactor, scaleFactor));
CGSize centerOffset = CGSizeMake((CGRectGetWidth(viewToFitIn.frame)-scaledSize.width)/(scaleFactor*2.0),
                                 (CGRectGetHeight(viewToFitIn.frame)-scaledSize.height)/(scaleFactor*2.0));
scaleTransform = CGAffineTransformTranslate(scaleTransform, centerOffset.width, centerOffset.height);
// End of "center in view" transformation code

CGPathRef scaledPath = CGPathCreateCopyByTransformingPath(shapeLayer.path,
                                                          &scaleTransform);

// Create a new shape layer and assign the new path
CAShapeLayer *scaledShapeLayer = [CAShapeLayer layer];
scaledShapeLayer.path = scaledPath;
scaledShapeLayer.fillColor = [UIColor blueColor].CGColor;
[viewToFitIn.layer addSublayer:scaledShapeLayer];

CGPathRelease(scaledPath); // release the copied path

在我的示例代码和形状中,它看起来像这样:

输入图像说明


谢谢,"居中显示" 真的很有帮助。 - MAMN84
我正在解决一个类似的问题,而且我不知道 CGPath 上存在这个 API。非常感谢你! - cbowns
1
只是一个小提示。您需要负责释放从CGPathCreateCopyByTransformingPath返回的CGPath。 - hjaltij

8

David Rönnqvist的回答的Swift 4.0版本

 func resizepath(Fitin frame : CGRect , path : CGPath) -> CGPath{


            let boundingBox = path.boundingBox
            let boundingBoxAspectRatio = boundingBox.width / boundingBox.height
            let viewAspectRatio = frame.width  / frame.height
            var scaleFactor : CGFloat = 1.0
            if (boundingBoxAspectRatio > viewAspectRatio) {
                // Width is limiting factor

                scaleFactor = frame.width / boundingBox.width
            } else {
                // Height is limiting factor
                scaleFactor = frame.height / boundingBox.height
            }


            var scaleTransform = CGAffineTransform.identity
            scaleTransform = scaleTransform.scaledBy(x: scaleFactor, y: scaleFactor)
            scaleTransform.translatedBy(x: -boundingBox.minX, y: -boundingBox.minY)

        let scaledSize = boundingBox.size.applying(CGAffineTransform (scaleX: scaleFactor, y: scaleFactor))
       let centerOffset = CGSize(width: (frame.width - scaledSize.width ) / scaleFactor * 2.0, height: (frame.height - scaledSize.height) /  scaleFactor * 2.0 )
        scaleTransform = scaleTransform.translatedBy(x: centerOffset.width, y: centerOffset.height)
        //CGPathCreateCopyByTransformingPath(path, &scaleTransform)
        let  scaledPath = path.copy(using: &scaleTransform)


        return scaledPath!
    }

3

这是基于Tarek的答案,但经过重构并修复了scaleFactor * 2bug的David Rönnqvist的Swift 5版本:

extension CGPath {
    func resized(to rect: CGRect) -> CGPath {
        let boundingBox = self.boundingBox
        let boundingBoxAspectRatio = boundingBox.width / boundingBox.height
        let viewAspectRatio = rect.width / rect.height
        let scaleFactor = boundingBoxAspectRatio > viewAspectRatio ?
            rect.width / boundingBox.width :
            rect.height / boundingBox.height

        let scaledSize = boundingBox.size.applying(CGAffineTransform(scaleX: scaleFactor, y: scaleFactor))
        let centerOffset = CGSize(
            width: (rect.width - scaledSize.width) / (scaleFactor * 2),
            height: (rect.height - scaledSize.height) / (scaleFactor * 2)
        )

        var transform = CGAffineTransform.identity
            .scaledBy(x: scaleFactor, y: scaleFactor)
            .translatedBy(x: -boundingBox.minX + centerOffset.width, y: -boundingBox.minY + centerOffset.height)

        return copy(using: &transform)!
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接