私はあなたがあなたの視界に合うように形を(歪ませることなく)完全に塗りつぶしたいと思っていると仮定しています。また、質問には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
私のサンプルコード(および形状)では、次のようになりました
