LoginSignup
38
34

More than 5 years have passed since last update.

Swift3.0で画像の切り抜き

Last updated at Posted at 2016-09-23

APIの命名規則も変わったようなので、それに合わせて作ってみました。

一応Retina画像(scale値2以上)でもポイント単位で指定してもらえれば正しく処理できる予定です。
また、元の画像がopaque(=不透明)かどうかも判定してイメージを生成しており、不透明の画像は不透明のフラグのままクロップされますので、クロップ後の画像の表示速度なども悪くはならない予定です。

extension UIImage {
    func cropping(to: CGRect) -> UIImage? {
        var opaque = false
        if let cgImage = cgImage {
            switch cgImage.alphaInfo {
            case .noneSkipLast, .noneSkipFirst:
                opaque = true
            default:
                break
            }
        }

        UIGraphicsBeginImageContextWithOptions(to.size, opaque, scale)
        draw(at: CGPoint(x: -to.origin.x, y: -to.origin.y))
        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return result
    }
}

使い方

let img = UIImage(named: "HIRAyamatoneko_TP_V")!

// クロップしたい矩形を指定するだけ
let cropping = img.cropping(to: CGRect(x: 176, y: 71, width: 106, height: 92))

こちらの画像が
HIRAyamatoneko_TP_V.png

クロップされました。
スクリーンショット 2016-09-23 15.37.18.png

※写真はフリー写真素材ぱくたそ様のものを使わせていただきました。

38
34
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
38
34