SwiftUI 实践

295 阅读1分钟

Q Identifiable

struct AppModel: Identifiable {
    let id: Int
    var primaryGenreId: Int
    var description: String
}

Q SwiftUI 如何调用项目中原来的 UIViewController, 思路:创建一个 ControllerWrapper, 实现 UIViewControllerRepresentable 协议,做相应的映射。

struct ControllerWrapper<T: UIViewController>: UIViewControllerRepresentable {
    typealias UIViewControllerType = T
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<ControllerWrapper>) -> ControllerWrapper.UIViewControllerType {
        return ControllerWrapper.UIViewControllerType()
    }
    func updateUIViewController(_ uiViewController: T, context: Context) {
        //
    }
}

// 例如:现在有一个 TextViewController,我们如何在 SwiftUI 点击某个 link 跳转到该页面。
NavigationLink(destination: ControllerWrapper<TextViewController>()) {
     Text("跳转到 TextViewController 页面")
 }

Q UIVIewController 里调用 SwiftUi 页面,将 SwiftUI 页面,放到一个 UIHostingController 里面,之后再正常跳转。

Q 读取本地 JSON 数据

Q ObservableObject 协议

  • @Published 属性包装器
  • objectWillChange

Q 属性观察器

  • will

Q GPUImage

  • 常见的颜色空间有 RGB 和 YCbCr。YCbCr 能够提供比 RGB 更好的压缩比,因为只需要保证 Y 分量精度够高,Cb 和 Cr 进行适当压缩不影响最后的体感质量,所以在视频相关领域中被广泛使用。
  1. CPU 方式 pixel-wise
uint *pixel_data =  rawData + i * width + j

#define Mask8(x) ( (x) & 0xFF )
#define R(x) ( Mask8(x) )
#define G(x) ( Mask8(x >> 8 ) )
#define B(x) ( Mask8(x >> 16) )
  1. GPU 方式
  • RGB->YUV:
varying mediump vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
void main()
{
    mediump vec3 yuv;
    mediump vec3 rgb;
    rgb = texture2D(inputImageTexture, textureCoordinate).rgb;
    yuv = mat3(0.256, -.148, .439,
                .504, -.291, -.368,
                0.098, .439,-.071 ) * rgb + vec3(16.0 / 255.0, 0.5, 0.5);
    gl_FragColor = vec4(yuv.r,0,0, 1);
}
  • YUV->RGB:
varying mediump vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
void main()
{
    mediump vec3 yuv;
    mediump vec3 rgb;
    yuv = texture2D(inputImageTexture, textureCoordinate).rgb - vec3(16.0/255.0, 0.5, 0.5);

    rgb = mat3(1.164, 1.164, 1.164,
                0, -.392, 2.017,
                1.596, -.813,0 ) * yuv;
    gl_FragColor = vec4(rgb, 1);
}

Q C 练习实例32