Swift 的新手,无法设法找到最确定的方法来更改我的代码,使其能够根据从用户库中选择的图像裁剪图像,并在 ImageView 中显示为完整的圆形图像。
此外,我如何像 https://github.com/ruslanskorb/RSKImageCropper 这样呈现和图像裁剪器?在一个快速的项目中?
这是我一直在尝试的代码:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let imagePicked = info[UIImagePickerControllerOriginalImage] as! UIImage
let borderWidth: CGFloat = 1.5
let cornerRadius:CGFloat = imageView.frame.height/2
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.blackColor().CGColor
imageView.clipsToBounds = true
// Create a multiplier to scale up the corner radius and border
// width you decided on relative to the imageViewer frame such
// that the corner radius and border width can be converted to
// the UIImage's scale.
let multiplier:CGFloat = imagePicked.size.height/imageView.frame.size.height > imagePicked.size.width/imageView.frame.size.width ?
imagePicked.size.height/imageView.frame.size.height :
imagePicked.size.width/imageView.frame.size.width
let borderWidthMultiplied:CGFloat = borderWidth * multiplier
let cornerRadiusMultiplied:CGFloat = cornerRadius * multiplier
UIGraphicsBeginImageContextWithOptions(imagePicked.size, false, 0)
let path = UIBezierPath(roundedRect: CGRectInset(CGRectMake(50, 50, imagePicked.size.width, imagePicked.size.height),
borderWidthMultiplied / 2, borderWidthMultiplied / 2), cornerRadius: cornerRadiusMultiplied)
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
// Clip the drawing area to the path
path.addClip()
// Draw the image into the context
imagePicked.drawInRect(CGRectMake(50, 50, imagePicked.size.width, imagePicked.size.height))
CGContextRestoreGState(context)
// Configure the stroke
UIColor.blackColor().setStroke()
path.lineWidth = borderWidthMultiplied
// Stroke the border
path.stroke()
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
print("picker cancel.")
}
最佳答案
要使图像成为圆形,您的 imageView 应该是方形的....首先从 UIimagepicker 获取图像并将此图像设置为 UIimageview,它应该是方形的(等宽和等高)和 UIimageview *imageView = CGRectMake(x-axis,y-axis,side,side);
imageView.layer.cornerRadius = side/2;
imageView.clipToBounds = YES;
设置UIimageview的圆角半径为正方形边高的一半 其次,您必须将 clipsToBounds 属性设置为 YES 才能使图层正常工作。
关于ios - 通过 UIimageview 和 uiimagepicker 显示圆形图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34646332/