1
2

More than 1 year has passed since last update.

【SwiftUI】画像の解像度を下げる

Posted at

はじめに

画像の解像度を下げる方法を調べたので記事にしておきます。

こんな感じになる

simulator_screenshot_DF2EAC46-82BA-499E-A4D5-9B2D154544A7.png

実装

import SwiftUI

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

    var body: some View {
        if let image = reduceResolution(of: image, scaleFactor: 0.1) {
            Image(uiImage: image)
                .resizable()
                .scaledToFit()
        }
    }

    func reduceResolution(of image: UIImage, scaleFactor: CGFloat) -> UIImage? {
        let newSize = CGSize(width: image.size.width * scaleFactor, height: image.size.height * scaleFactor)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.draw(in: CGRect(origin: .zero, size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
}

おわり

モザイクアプリとか作れそうですね

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