2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】CIFilterで画像の色数を制限する

Posted at

はじめに

CIFilterを使って画像の色数を制限してみます

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-10-23 at 22.45.10.gif

実装

import SwiftUI

struct ContentView: View {
    private let image = UIImage(named: "sample")!

    @State private var uiImage: UIImage?
    
    @State private var colorCount: Int = 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 {
                        applyColorPosterizeFilter()
                    } label: {
                        Text("適用")
                    }

                    Button {
                        uiImage = nil
                    } label: {
                        Text("リセット")
                    }
                }
                
                Stepper(value: $colorCount) {
                    Text("色数: \(colorCount)")
                }
            }
            .padding(.horizontal, 20)
        }
    }

    func applyColorPosterizeFilter() {
        let context = CIContext()
        let inputImage = CIImage(image: image)!

        guard let colorPosterizeFilter = CIFilter(name: "CIColorPosterize", parameters: [
            kCIInputImageKey: inputImage,
            "inputLevels": colorCount
        ]) else { return }
        guard let outputImage = colorPosterizeFilter.outputImage else { return }
        guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return }
        self.uiImage = UIImage(cgImage: cgImage)
    }
}

おわり

CIFilterはまだまだたくさんあるので一通り触ってみたいです

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?