iOS中图片的加载、圆角、阴影实现方式多种多样,我们需着重考虑性能问题
视图阴影
/// 为UIImageView设置阴影
///
/// - Parameters:
/// - color: The color of the shadow
/// - opacity: The opacity of the shadow.
/// - radius: The blur radius used to create the shadow.
/// - path: The shadow path.
func shadowView(_ color: UIColor, opacity: Float, radius: CGFloat ,path: CGPath) {
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowRadius = radius
// 使用shadowPath可以避免离屏渲染
layer.shadowPath = path
}
圆角图片
/// 圆角图片
///
/// - Parameter radius: 圆角
/// - Returns: 给定圆角的图片
func roundImg(radius: CGFloat, itemType: CompressItemType) -> UIImage {
var tempImg = UIImage()
// cell的size,即图片实际显示大小
let forSize = itemType.size()
// 开启上下文
UIGraphicsBeginImageContextWithOptions(forSize, false, UIScreen.main.scale)
// 设置路径
UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: forSize), cornerRadius: radius).addClip()
draw(in: CGRect(origin: CGPoint.zero, size: forSize))
tempImg = UIGraphicsGetImageFromCurrentImageContext()!
// 关闭上下文
UIGraphicsEndImageContext()
return tempImg
}
注意:这种方法能够避免离屏渲染,但是会占用大量的内存。还有直接对图层设置cornerRadius实现圆角和使用CAShapeLayer实现圆角的,但是这两种方法会产生离屏渲染。CAShapeLayer在iOS9.0以上设置mask不会产生离屏渲染