1
2

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

はじめに

CIFilter7日目です!

CIGaborGradientsを使用して線を強調します
垂直方向の線が緑の色、水平方向の線が赤い色になります。
これを活用して絵を描く際のサポートなんかになりそうです。

サンプルアプリ

Simulator Screen Recording - iPhone 15 - 2023-10-18 at 20.33.20.gif

実装

import SwiftUI

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

    @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 {
                        applyGaborGradientsFilter()
                    } label: {
                        Text("適用")
                    }
                    
                    Button {
                        uiImage = nil
                    } label: {
                        Text("リセット")
                    }
                }
            }
            .padding(.horizontal, 20)
        }
    }

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

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

おわり

いろんなFilterが標準で搭載されててすごいですね

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?