裁剪图像为圆形快速3 [英] Crop image to be circular swift 3

查看:80
本文介绍了裁剪图像为圆形快速3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,过去几天我一直在尝试解决此问题,但是找不到解决方案。我的问题很简单,我试图裁剪图像,使其变成一个圆圈。从完成的研究中,我发现了一些可用于实现此目的的方法,而且似乎弹出的主要方法是简单地裁剪UIImageView,使其成为圆形框架。我用来执行此操作的代码如下所示。

So I have this issue I have been trying to solve for the past few days however, cannot find a solution to the problem. My issue is very simple I am trying to crop a image so that it becomes a circle. From research done, I have found a few methods that can be used to achieve this and the main one which seemed to pop up a lot is to simply crop the UIImageView so that it becomes a circular frame. The code which I used to do this can be seen below.

imageView.layer.masksToBounds = false
imageView.layer.cornerRadius = imageView.frame.height/2
imageView.clipsToBounds = true

The唯一的问题是此方法仅裁剪图像视图的框架,而不裁剪图像本身。因此,例如,如果我要将图像保存到用户相机胶卷,它仍将显示为矩形而不是裁剪的圆形。我对如何真正实现这一目标感到迷茫,因为我对Xcode还是比较陌生,希望有人可以提供一种方法,使我可以裁剪图像本身而不仅仅是帧。任何有关该主题的帮助将不胜感激。谢谢。

The only problem is that this method only crops the frame of the image view and not the image itself. So if I was to save the image to the users camera roll for instance, it would still appear as a rectangle and not a cropped circle. I am a bit lost with how I can actually achieve this as I am relatively new to Xcode and was hoping that someone might be able to provide a method as to how I can crop the image itself not just the frame. Any help on the topic will be greatly appreciated. Thank you.

推荐答案

让我们开始谈谈**图形上下文
**。

Lets get on **Graphics Context **.

func makeRoundImg(img: UIImageView) -> UIImage {
    let imgLayer = CALayer()
    imgLayer.frame = img.bounds
    imgLayer.contents = img.image?.cgImage;
    imgLayer.masksToBounds = true;

    imgLayer.cornerRadius = 28 //img.frame.size.width/2

    UIGraphicsBeginImageContext(img.bounds.size)
    imgLayer.render(in: UIGraphicsGetCurrentContext()!)
    let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return roundedImage!;
}

这篇关于裁剪图像为圆形快速3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆