私は CGAffineTransform で回転させている UIImageView (フルフレームと長方形) を持っています。UIImageView の UIImage はフレーム全体を埋めます。イメージを回転して描画すると、エッジが著しくギザギザになります。見栄えを良くするためにできることはありますか?背景でアンチエイリアス処理されていないことは明らかです。
8 に答える
CoreAnimation レイヤーのエッジは、iOS ではデフォルトでアンチエイリアス処理されません。ただし、Info.plist で設定できる、エッジのアンチエイリアシングを有効にするキーがあります: UIViewEdgeAntialiasing.
このオプションを有効にすることによるパフォーマンスのオーバーヘッドを避けたい場合は、回避策として、画像の端に 1 ピクセルの透明な境界線を追加します。これは、画像の「端」が端にないことを意味するため、特別な処理は必要ありません!
新しい API – iOS 6/7
@Chris が指摘したように、iOS 6 でも動作しますが、iOS 7 まで公開されませんでした。
iOS 7 以降、CALayer にはallowsEdgeAntialiasing
、アプリケーションのすべてのビューに対して有効にするオーバーヘッドを発生させることなく、この場合に必要なことを正確に実行する新しいプロパティがあります! これは CALayer のプロパティであるため、使用する UIView でこれを有効にするには myView.layer.allowsEdgeAntialiasing = YES
.
画像に 1px の透明な境界線を追加するだけです
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0.0);
[image drawInRect:CGRectMake(1,1,image.size.width-2,image.size.height-2)];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
適切なアンチエイリアス オプションを設定することを忘れないでください。
CGContextSetAllowsAntialiasing(theContext, true);
CGContextSetShouldAntialias(theContext, true);
次のライブラリを完全にお勧めします。
http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
この問題を解決し、サムネイルなどを生成するためのコードも含む UIImage の便利な拡張機能が多数含まれています。
楽しみ!
私はここからこの解決策を見つけました、そしてそれは完璧です:
+ (UIImage *)renderImageFromView:(UIView *)view withRect:(CGRect)frame transparentInsets:(UIEdgeInsets)insets {
CGSize imageSizeWithBorder = CGSizeMake(frame.size.width + insets.left + insets.right, frame.size.height + insets.top + insets.bottom);
// Create a new context of the desired size to render the image
UIGraphicsBeginImageContextWithOptions(imageSizeWithBorder, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Clip the context to the portion of the view we will draw
CGContextClipToRect(context, (CGRect){{insets.left, insets.top}, frame.size});
// Translate it, to the desired position
CGContextTranslateCTM(context, -frame.origin.x + insets.left, -frame.origin.y + insets.top);
// Render the view as image
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
// Fetch the image
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
// Cleanup
UIGraphicsEndImageContext();
return renderedImage;
}
利用方法:
UIImage *image = [UIImage renderImageFromView:view withRect:view.bounds transparentInsets:UIEdgeInsetsZero];