swift UIImage 圆形图标:
import UIKit
extension UIImageView{
/**
* 设置圆形的图片
* param: urlStr 网络图片地址
* param: placeholderStr 占位图片名称
* param: radius 圆角半径
*/
func setImageOfRound(urlStr:String,placeholderStr:String,radius:CGFloat){
let url = URL(string: urlStr)
let urlRequest = URLRequest(url: url!)
self.setImageWith(urlRequest, placeholderImage:UIImage(named: placeholderStr), success: {(urlRequest,response,image)->Void in
self.image = image //这句一定要比self.cornerRadius(radius: radius)先执行
self.cornerRadius(radius: radius)
//
}, failure: {
(urlRequest,response,error)->Void in
})
}
/**
* param: radius 圆角半径
* 注意:只有当imageView.image不为nil时,调用此方法才有效果
*/
func cornerRadius(radius:CGFloat){
//开始图形上下文
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
//获取图形上下文
let ctx = UIGraphicsGetCurrentContext()
//根据一个rect创建一个椭圆
ctx!.addEllipse(in: self.bounds)
//裁剪
ctx!.clip()
//将原照片画到图形上下文
self.image!.draw(in: self.bounds)
//从上下文上获取剪裁后的照片
let newImage = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()
self.image = newImage
}
}
网友评论