81 lines
2.6 KiB
Swift
81 lines
2.6 KiB
Swift
//
|
||
// SPFadeEdgeImageView.swift
|
||
// MoviaBox
|
||
//
|
||
// Created by 佳尔 on 2025/4/28.
|
||
//
|
||
|
||
import UIKit
|
||
|
||
class SPFadeEdgeImageView: UIImageView {
|
||
|
||
override var image: UIImage? {
|
||
didSet {
|
||
applyBlurAndEdgeFadeEffect()
|
||
}
|
||
}
|
||
|
||
private var blurredImage: UIImage?
|
||
|
||
override func layoutSubviews() {
|
||
super.layoutSubviews()
|
||
applyBlurAndEdgeFadeEffect()
|
||
}
|
||
|
||
private func applyBlurAndEdgeFadeEffect() {
|
||
if blurredImage != nil, blurredImage == image {
|
||
return
|
||
}
|
||
// 1. 添加高斯模糊效果到图片
|
||
let context = CIContext(options: nil)
|
||
guard let image = self.image else { return }
|
||
guard let ciImage = CIImage(image: image) else { return }
|
||
|
||
let filter = CIFilter(name: "CIGaussianBlur")
|
||
filter?.setValue(ciImage, forKey: kCIInputImageKey)
|
||
filter?.setValue(50, forKey: kCIInputRadiusKey) // 调整模糊半径
|
||
guard let outputImage = filter?.outputImage else { return }
|
||
|
||
if let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
|
||
let blurredImage = UIImage(cgImage: cgImage)
|
||
self.blurredImage = blurredImage
|
||
self.image = blurredImage
|
||
}
|
||
|
||
// 2. 创建渐变蒙版(四周虚化)
|
||
let maskLayer = CAShapeLayer()
|
||
maskLayer.frame = bounds
|
||
|
||
// 画一个圆形的反向路径,中心完全显示,四周渐变透明
|
||
let path = UIBezierPath(rect: bounds)
|
||
let insetRect = bounds.insetBy(dx: bounds.width * 0.1, dy: bounds.height * 0.1)
|
||
let innerPath = UIBezierPath(roundedRect: insetRect, cornerRadius: 20)
|
||
path.append(innerPath)
|
||
path.usesEvenOddFillRule = true
|
||
|
||
maskLayer.path = path.cgPath
|
||
maskLayer.fillRule = .evenOdd
|
||
|
||
// 3. 创建径向渐变图层
|
||
let gradientLayer = CAGradientLayer()
|
||
gradientLayer.frame = bounds
|
||
gradientLayer.colors = [
|
||
UIColor.black.withAlphaComponent(1).cgColor,
|
||
UIColor.black.withAlphaComponent(0).cgColor
|
||
]
|
||
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
|
||
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
|
||
gradientLayer.locations = [0.5, 1]
|
||
gradientLayer.type = .radial
|
||
|
||
// 4. 添加渐变蒙版到图片
|
||
let containerLayer = CALayer()
|
||
containerLayer.frame = bounds
|
||
containerLayer.addSublayer(gradientLayer)
|
||
containerLayer.mask = maskLayer
|
||
|
||
self.layer.mask = containerLayer
|
||
}
|
||
|
||
}
|