我假设您想要完全填充(不扭曲)形状以适合您的视图。我还假设您已经有一个带有路径的形状层,因为问题被标记为 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
在我的示例代码(和形状)中,它看起来像这样