UIImageの角を丸くする

UIImageのカテゴリメソッドとして増やすと以下のように使えるので大変に便利です。

UIImage *image = [UIImage imageNamed:@"something"];
self.imageView = [image imageWithCornerRadius:4.0];

/**
 Round off the corner of UIImage.
 */
- (UIImage *)imageWithCornerRadius:(CGFloat)cornerRadius
{
  UIImage *resultImage;
  UIImage *maskImage;
  CGRect imageBounds = (CGRect){CGPointZero, self.size};

  // Make mask image
  UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:imageBounds cornerRadius:cornerRadius];
  UIGraphicsBeginImageContextWithOptions(path.bounds.size, NO, 0.0);
  [[UIColor blackColor] setFill];
  [path fill];
  maskImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  // Draw image
  UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextClipToMask(context, imageBounds, [maskImage CGImage]);
  [self drawAtPoint:CGPointZero];
  resultImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return resultImage;
}

Pocket
LINEで送る
LinkedIn にシェア

コメントを残す