是否可以 trim 将 UIImage 转为圆形?

Is it possible to trim a UIImage to circular form?

我想知道是否可以设置 UIImage 的角半径,然后保存修剪后的 UIImage(以解析)。

我希望上传到 Parse 的图像是圆形的,我想知道是否可以像这样设置圆角半径,然后将图像上传到 Parse。 parse 会将图像保存为这样吗?

meImage.layer.cornerRadius = meImage.frame.size.width/2

您需要绘制图像。试试这个-

- (UIImage *)imageByDrawingCircleOnImage:(UIImage *)image
{
  UIGraphicsBeginImageContext(image.size);
  [image drawAtPoint:CGPointZero];
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  [[UIColor redColor] setStroke];

  // make circle rect 5 px from border
  CGRect circleRect = CGRectMake(0, 0,
                          image.size.width,
                               image.size.height);
  circleRect = CGRectInset(circleRect, 5, 5);
  CGContextStrokeEllipseInRect(ctx, circleRect);
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return image ;

}

嗯,我不知道你为什么接受那个答案,它根本不符合你的要求。

你的问题最直接的答案是这个,不,不可能 trim 一个图像数据表示为一个圆,它们总是一个矩形..所以下一个最好的事情是使不在圆圈内的图像部分透明。
为了使其正常工作,当您将 NSData 表示形式上传到服务器时,您需要使用支持透明度的数据表示形式。在 iOs 中,这意味着使用 PNG 格式而不是 JPG 格式。

好的,这里有一些代码可以做到这一点。

//i'd put this in a category on UIImage, therefore we don't need a pointer to the original image, which will be 'self'

-(UIImage *)imageCroppedToCircleOfDiameter:(CGFloat )diameter{

//most images will be rectangular, (height != width)
//so work out how it is going to scale
CGFloat scale = CGFloat(fmaxf(diameter/self.size.width, diameter/self.size.height) );

CGRect imageRct = CGRectZero; //where we'l draw the image
CGRect circleRct = CGRectZero; //where we'll 'cut' a circle from the context

circleRct.size.width = circleRct.size.height = diameter;

imageRct.size.width = self.size.width*scale;
imageRct.size.height = self.size.height*scale;
imageRct.origin.x = ((self.size.height>self.size.width)? 0.0: ((imageRct.size.height-imageRct.size.width)/2.0)   );
imageRct.origin.y = ((self.size.width>self.size.height)? 0.0: ((imageRct.size.width-imageRct.size.height)/2.0)   );



UIGraphicsBeginImageContextWithOptions(circleRct.size, NO, 0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextAddEllipseInRect( ctx, circleRct);
CGContextClip(context);

[self drawInRect:imageRct];


CGContextRestoreGState(ctx);

 UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

 return result;
}