裁剪图像为圆形快速3

时间:2017-09-19 12:01:05

标签: swift3 uiimageview drawing crop

所以我有这个问题我过去几天一直试图解决,但是找不到问题的解决方案。我的问题非常简单,我正在尝试裁剪图像,使其成为一个圆圈。从研究完成后,我发现了一些可用于实现此目的的方法,而且似乎突然出现的主要方法是简单地裁剪UIImageView以使其成为圆形框架。我用来做这个的代码可以在下面看到。

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

唯一的问题是此方法仅裁剪图像视图的帧而不是图像本身。因此,如果我要将图像保存到用户相机胶卷,它仍然会显示为矩形而不是裁剪的圆圈。由于我对Xcode相对较新,并希望有人能够提供一种关于如何裁剪图像本身而不仅仅是框架的方法,我对实际如何实现这一点感到有些迷茫。任何有关该主题的帮助将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:4)

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

enter image description here

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!;
}

答案 1 :(得分:3)

尝试 swift 3 的此代码,首先您需要将imageView内容模式保持为Aspect Fit。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var imgView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    let profilePicture = UIImage(named: "yourImageName")
    self.imgView.image = profilePicture.circleMasked
   }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



}

  extension UIImage {
  var isPortrait:  Bool    { return size.height > size.width }
  var isLandscape: Bool    { return size.width > size.height }
  var breadth:     CGFloat { return min(size.width, size.height) }
  var breadthSize: CGSize  { return CGSize(width: breadth, height: breadth) }
  var breadthRect: CGRect  { return CGRect(origin: .zero, size: breadthSize) }
  var circleMasked: UIImage? {
      UIGraphicsBeginImageContextWithOptions(breadthSize, false, scale)
      defer { UIGraphicsEndImageContext() }
      guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(x: isLandscape ? floor((size.width - size.height) / 2) : 0, y: isPortrait  ? floor((size.height - size.width) / 2) : 0), size: breadthSize)) else { return nil }
      UIBezierPath(ovalIn: breadthRect).addClip()
      UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation).draw(in: breadthRect)
      return UIGraphicsGetImageFromCurrentImageContext()
  }
}

答案 2 :(得分:1)

尝试以下

imageView.layer.masksToBounds = false
imageView.layer.cornerRadius = imageView.frame.height/2
imageView.layer.borderWidth = 1
imageVoew.layer.borderColor = UIColor.clear.cgColor
imageView.clipsToBounds = true