index.uts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { UIView } from "UIKit";
  2. import { SVGKFastImageView, SVGKImage } from "SVGKit";
  3. /**
  4. * CoolSvg iOS 平台 SVG 渲染器
  5. * - 本地文件路径
  6. */
  7. export class CoolSvg {
  8. /** uni-app x 原生视图元素 */
  9. $element: UniNativeViewElement;
  10. /** iOS SVGKFastImageView 实例 */
  11. imageView: SVGKFastImageView | null = null;
  12. /**
  13. * 构造函数
  14. * @param element uni-app x 原生视图元素
  15. */
  16. constructor(element: UniNativeViewElement) {
  17. this.$element = element;
  18. // 创建占位符 SVG 图像
  19. let placeholderImage = SVGKImage((contentsOf = URL((fileURLWithPath = ""))));
  20. // 初始化 SVG 图像视图
  21. this.imageView = new SVGKFastImageView((svgkImage = placeholderImage));
  22. // 将视图绑定到 uni-app x 元素
  23. this.$element.bindIOSView(this.imageView!);
  24. }
  25. /**
  26. * 加载并渲染 SVG
  27. * @param src SVG 数据源
  28. * @param color 填充颜色,用于替换 SVG 中 path 元素的 fill 属性
  29. */
  30. load(src: string, color: string) {
  31. // 空字符串检查
  32. if (src == "") {
  33. return;
  34. }
  35. try {
  36. // 从资源路径加载 SVG 图像
  37. let svgImage = SVGKImage(
  38. (contentsOf = URL((fileURLWithPath = UTSiOS.getResourcePath(src))))
  39. );
  40. // 加载失败检查
  41. if (svgImage == null) {
  42. return;
  43. }
  44. // 设置 SVG 图像到视图
  45. this.imageView!.image = svgImage;
  46. // 应用颜色覆盖
  47. if (color != "") {
  48. // 创建颜色覆盖层视图
  49. let colorView = new UIView();
  50. colorView.frame = this.imageView!.bounds;
  51. colorView.backgroundColor = UTSiOS.colorWithString(color);
  52. // 设置合成滤镜为 sourceAtop,实现颜色覆盖效果
  53. colorView.layer.compositingFilter = "sourceAtop";
  54. this.imageView!.addSubview(colorView);
  55. }
  56. } catch (e) {
  57. // 静默处理异常,避免影响应用运行
  58. }
  59. }
  60. }