54 lines
1.6 KiB
Swift
54 lines
1.6 KiB
Swift
//
|
||
// SPFadeEdgeImageView.swift
|
||
// ThimraTV
|
||
//
|
||
// Created by 佳尔 on 2025/4/28.
|
||
//
|
||
|
||
import UIKit
|
||
|
||
class SPFadeEdgeImageView: UIImageView {
|
||
|
||
|
||
private var blurredImage: UIImage?
|
||
|
||
override func layoutSubviews() {
|
||
super.layoutSubviews()
|
||
|
||
applyCircularFade()
|
||
}
|
||
|
||
/// 给当前视图添加一个圆形渐隐遮罩
|
||
func applyCircularFade(radius: CGFloat? = nil) {
|
||
let maskLayer = CALayer()
|
||
maskLayer.frame = bounds
|
||
|
||
// 渲染一个径向渐变图像
|
||
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
|
||
guard let ctx = UIGraphicsGetCurrentContext() else { return }
|
||
|
||
let center = CGPoint(x: bounds.midX, y: bounds.midY)
|
||
let maxRadius = radius ?? min(bounds.width, bounds.height) / 2
|
||
|
||
let colorSpace = CGColorSpaceCreateDeviceGray()
|
||
let colors: [CGFloat] = [1, 1, 0, 0] // 中心透明度1,边缘透明度0
|
||
let locations: [CGFloat] = [0, 1]
|
||
|
||
if let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colors, locations: locations, count: 2) {
|
||
ctx.drawRadialGradient(
|
||
gradient,
|
||
startCenter: center, startRadius: 0,
|
||
endCenter: center, endRadius: maxRadius,
|
||
options: .drawsAfterEndLocation
|
||
)
|
||
}
|
||
|
||
let maskImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage
|
||
UIGraphicsEndImageContext()
|
||
|
||
maskLayer.contents = maskImage
|
||
self.layer.mask = maskLayer
|
||
}
|
||
|
||
}
|