我正在使用imagePickerController从用户库中选择一张图片.我需要在应用程序中保存带圆角和边框的图片.保存图像时,它会保存未经改动的图像.我假设我只改变视图而不是图像本身.有没有办法将图片保存为视图中可以看到的内容?
@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
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!
您需要执行的基本操作是:
然后描绘用于剪裁的路径
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)
}
Run Code Online (Sandbox Code Playgroud)在上面的代码中,我将路径插入了笔划宽度的一半,因为笔划是沿着路径的中心绘制的,这意味着一个像素将最终在路径之外.
小智 5
带边框的圆形 UIImage:
extension UIImage {
func roundedWithStroke(width: CGFloat = 3) -> UIImage {
let imageLayer = CALayer()
let targetSize = CGSize(width: 29, height: 29)
imageLayer.frame = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
imageLayer.contents = cgImage
imageLayer.masksToBounds = true
imageLayer.cornerRadius = targetSize.width / 2
imageLayer.borderWidth = width
imageLayer.borderColor = UIColor.mainAccent.cgColor
UIGraphicsBeginImageContextWithOptions(targetSize, false, scale)
imageLayer.render(in: UIGraphicsGetCurrentContext()!)
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundedImage ?? UIImage()
}
}
Run Code Online (Sandbox Code Playgroud)
您可以修改扩展方法以传递您需要的参数。
| 归档时间: |
|
| 查看次数: |
10250 次 |
| 最近记录: |