使用圆角保存UIImage并使用Swift边框 [英] Saving UIImage with rounded corners and border with Swift

查看:148
本文介绍了使用圆角保存UIImage并使用Swift边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用imagePickerController从用户库中选择一张图片。我需要在应用程序中保存带圆角和边框的图片。保存图像时,它会保存未经改动的图像。我假设我只改变视图而不是图像本身。有没有办法将图片保存为视图中可以看到的内容?

I am using imagePickerController to pick a picture form the users library. I need to save the picture within the app with rounded corners and a border. When I save the image, it saves the unaltered image. I'm assuming that I am only altering the view not the image itself. Is there a way to save the picture as what can be seen in the view?

@IBOutlet var imageViewer: UIImageView!

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    var imagePicked = info[UIImagePickerControllerOriginalImage] as UIImage
    imageViewer.layer.cornerRadius = 10.0
    imageViewer.clipsToBounds = true
    imageViewer.layer.frame = CGRectInset(imageViewer.layer.frame, 20, 20)
    imageViewer.layer.borderColor = UIColor.purpleColor().CGColor
    imageViewer.layer.borderWidth = 2.0
    imageViewer.image = imagePicked

谢谢你的支持帮助!

推荐答案

您需要执行的基本操作是:

The basic operations you need to perform are:


  • 剪裁绘图区域以在没有角落的情况下绘制图像

  • 绘制图像

  • 配置笔触颜色等

  • 然后描绘用于裁剪的路径

  • Clip the drawing area to draw your image into without the corners
  • Draw the image
  • Configure the stroke colour etc
  • Then stroke the path used for clipping

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
  let borderWidth: CGFloat = 2.0
  let imagePicked = info[UIImagePickerControllerOriginalImage] as UIImage

  UIGraphicsBeginImageContextWithOptions(imageViewer.frame.size, false, 0)

  let path = UIBezierPath(roundedRect: CGRectInset(imageViewer.bounds, borderWidth / 2, borderWidth / 2), cornerRadius: 10.0)
  let context = UIGraphicsGetCurrentContext()

  CGContextSaveGState(context)
  // Clip the drawing area to the path
  path.addClip()

  // Draw the image into the context
  imagePicked.drawInRect(imageViewer.bounds)
  CGContextRestoreGState(context)

  // Configure the stroke
  UIColor.purpleColor().setStroke()
  path.lineWidth = borderWidth

  // Stroke the border
  path.stroke()

  roundedImage = UIGraphicsGetImageFromCurrentImageContext();

  UIGraphicsEndImageContext();

  view.addSubview(UIImageView(image: roundedImage))

  picker.dismissViewControllerAnimated(true, completion: nil)
}


在上面的代码中,我将路径插入了一半的笔划宽度,因为沿着路径的中心绘制笔划,这意味着一个像素将在路径之外结束。

In the code above I've inset the path by half of the stroke width because the stroke is drawn along the center of the path, which means that one pixel will end up outside the path.

这篇关于使用圆角保存UIImage并使用Swift边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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