如何在照片中保存圆形图像

时间:2016-10-08 12:31:12

标签: ios swift

我想在照片库中保存圆形图像。我正在尝试,但保存的图像并非四舍五入。

extension UIImage {
convenience init(view: UIView) {
    UIGraphicsBeginImageContextWithOptions(view.frame.size, view.opaque, 0)

    view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)

    view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()
    self.init(CGImage: image.CGImage!)
}
}
//calling 
let image = UIImage(view: myView)
 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

2 个答案:

答案 0 :(得分:0)

您只能将图片保存在图库中,但是您需要在看到以下代码后进行修改:

使用以下功能进行图像舍入。

在Swift中:

func maskRoundedImage(image: UIImage, radius: Float) -> UIImage {
    var imageView: UIImageView = UIImageView(image: image)
    var layer: CALayer = CALayer()
    layer = imageView.layer

    layer.masksToBounds = true
    layer.cornerRadius = CGFloat(radius)

    UIGraphicsBeginImageContext(imageView.bounds.size)
    layer.renderInContext(UIGraphicsGetCurrentContext())
    var roundedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return roundedImage
}

在目标C中:

-(UIImage *)makeRoundedImage:(UIImage *) image radius: (float) radius{
    CALayer *imageLayer = [CALayer layer];
    imageLayer.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    imageLayer.contents = (id) image.CGImage;

    imageLayer.masksToBounds = YES;
    imageLayer.cornerRadius = radius;

    UIGraphicsBeginImageContext(image.size);
    [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return roundedImage;
}

以下函数将返回一个圆角图像,您需要传递imagevalue才能使其圆整。

答案 1 :(得分:-1)

在您的扩展程序中尝试此操作:

view.layer.cornerRadius = 20.0f;

您可以调整该值以创建不同的舍入值。