58
61

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 5 years have passed since last update.

SwiftでUIImageを回転、リサイズ、クリッピング、塗りつぶし

Posted at

Objective-Cで色々書いていたので、どうせならswiftで残しておこうと思いまして。
Playgroundをそのまま貼り付けてます。

ImageUtilPlayground.swift
import UIKit

// URLで画像を取得
let url = NSURL(string: "http://placehold.jp/300x300.png")
var err: NSError?
let data :NSData = NSData(contentsOfURL: url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)!
let image = UIImage(data: data)!


// そのまま表示
let view1: UIImageView = UIImageView(frame: CGRectMake(0,0,300,300))
view1.image = image

// リサイズ
let size = CGSize(width: 150, height: 150)
UIGraphicsBeginImageContext(size)
image.drawInRect(CGRectMake(0, 0, size.width, size.height))
var resizeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let view2: UIImageView = UIImageView(frame: CGRectMake(0,0,150,150))
view2.image = resizeImage

// クリッピング
let cropCGImageRef = CGImageCreateWithImageInRect(image.CGImage, CGRectMake(0, 0, 150, 150))
var cropImage = UIImage(CGImage: cropCGImageRef)
let view3: UIImageView = UIImageView(frame: CGRectMake(0,0,150,150))
view3.image = cropImage

// 回転
var rotateImage = UIImage(CGImage: image.CGImage, scale: 1.0, orientation: UIImageOrientation.Right)
let view4: UIImageView = UIImageView(frame: CGRectMake(0, 0, 300, 300))
view4.image = rotateImage

// 色塗りつぶし
UIGraphicsBeginImageContext(size)
let cgContextRef = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(cgContextRef, UIColor.grayColor().CGColor)
CGContextSetAlpha(cgContextRef, 0.8)
CGContextFillRect(cgContextRef, CGRectMake(0, 0, 300, 300))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let view5: UIImageView = UIImageView(frame: CGRectMake(0,0,300,300))
view5.image = colorImage


58
61
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
58
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?