1 2 3 4 5 6 7 8 9 10 11 | //获取图片 let image = UIImage (named: "image1" ) //创建imageView let imageView = UIImageView (image: image) imageView.frame = CGRect (x:40, y:40, width:100, height:100) imageView.contentMode = .scaleAspectFill //设置遮罩 imageView.layer.masksToBounds = true //设置圆角半径(宽度的一半),显示成圆形。 imageView.layer.cornerRadius = imageView.frame.width/2 self .view.addSubview(imageView) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | extension UIImage { //生成圆形图片 func toCircle() -> UIImage { //取最短边长 let shotest = min ( self .size.width, self .size.height) //输出尺寸 let outputRect = CGRect (x: 0, y: 0, width: shotest, height: shotest) //开始图片处理上下文(由于输出的图不会进行缩放,所以缩放因子等于屏幕的scale即可) UIGraphicsBeginImageContextWithOptions (outputRect.size, false , 0) let context = UIGraphicsGetCurrentContext ()! //添加圆形裁剪区域 context.addEllipse( in : outputRect) context.clip() //绘制图片 self .draw( in : CGRect (x: (shotest- self .size.width)/2, y: (shotest- self .size.height)/2, width: self .size.width, height: self .size.height)) //获得处理后的图片 let maskedImage = UIGraphicsGetImageFromCurrentImageContext ()! UIGraphicsEndImageContext () return maskedImage } } |
1 2 3 4 5 6 | //获取图片 let image = UIImage (named: "image1" )?.toCircle() //创建imageView let imageView = UIImageView (image: image) imageView.frame = CGRect (x:40, y:40, width:100, height:100) self .view.addSubview(imageView) |
文章来源网络:点击这里查看源文.