はじめに
CIFilterで画像をピクセル化することができるっぽいのでやってみました
サンプルアプリ
実装
import SwiftUI
struct ContentView: View {
private let image = UIImage(named: "sample1")!
@State private var uiImage: UIImage?
@State private var scale: CGFloat = 0
var body: some View {
ScrollView {
VStack {
if let uiImage {
Image(uiImage: uiImage)
.resizable()
.scaledToFit()
} else {
Image(uiImage: image)
.resizable()
.scaledToFit()
}
HStack(spacing: 15) {
Button {
applyPixellate()
} label: {
Text("適用")
}
Button {
uiImage = nil
scale = 0
} label: {
Text("リセット")
}
}
VStack {
Text("粒度: \(scale)")
Slider(value: $scale, in: 0...50)
}
}
.padding(.horizontal, 20)
}
}
func applyPixellate() {
let context = CIContext()
let inputImage = CIImage(image: image)!
guard let filter = CIFilter(name: "CIPixellate", parameters: [
kCIInputImageKey: inputImage,
kCIInputScaleKey: scale
]) 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)
}
}
おわり
これだけで簡単なアプリが作れそうですね