はじめに
CIFilterを使ってX線写真のようなフィルターを作成します
サンプルアプリ
実装
import SwiftUI
struct ContentView: View {
private let image = UIImage(named: "sample1")!
@State private var uiImage: UIImage?
var body: some View {
ScrollView {
VStack {
if let uiImage {
Image(uiImage: uiImage)
.resizable()
.scaledToFit()
} else {
Image(uiImage: image)
.resizable()
.scaledToFit()
}
HStack(spacing: 15) {
Button {
applyXRay()
} label: {
Text("適用")
}
Button {
uiImage = nil
} label: {
Text("リセット")
}
}
}
.padding(.horizontal, 20)
}
}
func applyXRay() {
let context = CIContext()
let inputImage = CIImage(image: image)!
guard let filter = CIFilter(name: "CIXRay", parameters: [
kCIInputImageKey: inputImage
]) else { return }
guard let outputImage = filter.outputImage else { return }
guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return }
self.uiImage = UIImage(cgImage: cgImage)
}
}
おわり
これはいつ使うんでしょうか笑