Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
60
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

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

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


Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
60
Help us understand the problem. What are the problem?