2

幅500、高さ500の円であるいくつかのUIButtonのスクリーンショットを撮っています。スクリーンショットは正方形でしか作成できず、画像の周りに白い角ができたくないので、次のコードを使用しました。

UIGraphicsBeginImageContext(self.Button3.layer.bounds.size);
[self.Button3.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* image2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

    NSData* data = UIImagePNGRepresentation(image);
    [data writeToFile:BusinessCardPath atomically:YES];

これは完全に機能します。白い角のない円のみの写真が返されます。ただし、ピクセルが失われるため拡大できます。また、UIButton の上にある UILabels などのすべての要素がショットに含まれているわけではありませんが、UIButton のサブビューは含まれていません。

このコードを使用する場合:

CGSize imageSize = CGSizeMake(310, 310);

UIGraphicsBeginImageContext(self.Button3.layer.bounds.size);

CGContextRef context = UIGraphicsGetCurrentContext();
/*CGContextTranslateCTM(context, -5, -50);*/
// Iterate over every window from back to front
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
    if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
    {
        // -renderInContext: renders in the coordinate space of the layer,
        // so we must first apply the layer's geometry to the graphics context
        CGContextSaveGState(context);
        // Center the context around the window's anchor point
        CGContextTranslateCTM(context, [window center].x, [window center].y);
        // Apply the window's transform about the anchor point
        CGContextConcatCTM(context, [window transform]);
        // Offset by the portion of the bounds left of and above the anchor point
        CGContextTranslateCTM(context,
                              -[window bounds].size.width * [[window layer] anchorPoint].x,
                              -[window bounds].size.height * [[window layer] anchorPoint].y);

        // Render the layer hierarchy to the current context
        [[window layer] renderInContext:context];

        // Restore the context
        CGContextRestoreGState(context);
    }
}

// Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

・・・逆効果です。上記の要素は高解像度のスクリーンショットに含まれていますが、画像の周りに白い角があります。

4

1 に答える 1

2

CAShapeLayer を使用して、画像の一部をマスクできます。.path プロパティは、レンダリングされる領域を定義するために使用されます。

UIImageView *myImageView = [UIImageView alloc] init];
myImageView.image = [UIImage imageNamed:@"anImage.gif"];
[myImageView setClipsToBounds:YES];

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:myImageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(48, 48)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = myImageView.bounds;
maskLayer.path = maskPath.CGPath;

myImageView.layer.mask = maskLayer;

それはあなたに円のイメージを与えるはずです。半径で遊ぶ必要があるかもしれません。

于 2013-08-29T15:57:19.237 に答える