如何将阴影添加到UIImageView本身而不是其图层



我用这种方法向UIImageView添加阴影:

extension UIImageView {
public func applyShadow()
layer.shadowColor = UIColor.gray.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowOpacity = 0.2
layer.shadowRadius = 8.0
layer.masksToBounds = false
}
}

我希望内容模式.scaleAspectFit。但是,当我设置它时,layer的帧与UIImageView的帧不同,但我希望将阴影应用于UIImageView的帧。我怎样才能做到这一点?

解决方案是将UIImageView的背景颜色设置为白色。如果没有颜色集,图像的左右两侧没有内容,因此阴影在.scaleAspectFit图像上折叠。使用颜色集,阴影将应用于实际帧。

你必须通过用阴影爬行新图像来添加阴影来映像其自身

extension UIImageView {
func addShadowToImageNotLayer(blurSize: CGFloat = 8.0){
let shadowColor = UIColor(white:0.0, alpha:0.8).cgColor
guard let image = self.image else {return}
let context = CGContext(data: nil,
width: Int(image.size.width + blurSize),
height: Int(image.size.height + blurSize),
bitsPerComponent: image.cgImage!.bitsPerComponent,
bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
context.setShadow(offset: CGSize(width: blurSize/2,height: -blurSize/2),
blur: blurSize,
color: shadowColor)
context.draw(image.cgImage!,
in: CGRect(x: 0, y: blurSize, width: image.size.width, height: image.size.height),
byTiling:false)
self.image = UIImage(cgImage: context.makeImage()!)
}
}

使用:

UIImageView().addShadowToImageNotLayer(blurSize: 20)

最新更新