很多朋友都还在2行代码切圆角吧.......
哈哈 今天放出代码 直接拖进你的项目就能用了.不用再被人家嘲笑.
直接放出2个分类,
基于SDWebImage封装
//
// UIImageView+WebImage.swift
//
// Created by Jonson on 17/3/13.
//
import UIKit
extension UIImage {
/// 创建头像图像
///
/// - parameter size: 尺寸
/// - parameter backColor: 背景颜色
///
/// - returns: 裁切后的图像
func ht_avatarImage(size: CGSize?, backColor: UIColor = UIColor.white, lineColor: UIColor = UIColor.lightGray) -> UIImage? {
var size = size
if size == nil {
size = self.size
}
let rect = CGRect(origin: CGPoint(), size: size!)
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
backColor.setFill()
UIRectFill(rect)
let path = UIBezierPath(ovalIn: rect)
path.addClip()
draw(in: rect)
let ovalPath = UIBezierPath(ovalIn: rect)
ovalPath.lineWidth = 2
lineColor.setStroke()
ovalPath.stroke()
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
/// 生成指定大小的不透明图象
///
/// - parameter size: 尺寸
/// - parameter backColor: 背景颜色
///
/// - returns: 图像
func ht_image(size: CGSize? = nil, backColor: UIColor = UIColor.white) -> UIImage? {
var size = size
if size == nil {
size = self.size
}
let rect = CGRect(origin: CGPoint(), size: size!)
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
backColor.setFill()
UIRectFill(rect)
draw(in: rect)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
第二个
//
// UIImageView+WebImage.swift
//
// Created by Jonson on 17/3/13.
//
import SDWebImage
extension UIImageView {
/// 隔离 SDWebImage 设置图像函数
///
/// - parameter urlString: urlString
/// - parameter placeholderImage: 占位图像
/// - parameter isAvatar: 是否头像
func ht_setImage(urlString: String?, placeholderImage: UIImage?, isAvatar: Bool = false) {
// 处理 URL
guard let urlString = urlString,
let url = URL(string: urlString) else {
// 设置占位图像
image = placeholderImage
return
}
// 可选项只是用在 Swift,OC 有的时候用 ! 同样可以传入 nil
sd_setImage(with: url, placeholderImage: placeholderImage, options: [], progress: nil) { [weak self] (image, _, _, _) in
// 完成回调 - 判断是否是头像
if isAvatar {
self?.image = image?.ht_avatarImage(size: self?.bounds.size)
}
}
}
}
最后调用
iconView.ht_setImage(urlString: model.image, placeholderImage: UIImage(named: "default_image"), isAvatar: true)
网友评论