更多圖片處理方法見圖片組件 BBWebImage
iOS 圖片裁剪 + 旋轉
之前分別介紹了圖片裁剪和圖片旋轉方法
地址:http://www.cnblogs.com/silence-cnblogs/p/6490037.html
地址:http://www.cnblogs.com/silence-cnblogs/p/6496564.html
裁剪和旋轉是可以連在一起執行的。先定位到需要裁剪的區域,然后以此區域的中心為軸,旋轉一定角度,最后獲取旋轉后此區域內的圖片。可以用位圖(Bitmap)繪制實現
static func cropImage(_ image: UIImage, withRect rect: CGRect, angle: Double) -> UIImage? {
// Creates a bitmap-based graphics context with rect size
// and makes it the current context
UIGraphicsBeginImageContext(rect.size)
// Get current graphics context
guard let context = UIGraphicsGetCurrentContext() else { return nil }
// Move context origin to rect center
context.translateBy(x: rect.width / 2, y: rect.height / 2)
// Convert angle to radian and rotate
context.rotate(by: CGFloat(angle / 180 * M_PI))
// Move context origin back (-rect.width / 2, -rect.height / 2)
// and move opposite direction of rect origin (-rect.minX, -rect.minY)
context.translateBy(x: -rect.width / 2 - rect.minX, y: -rect.height / 2 - rect.minY)
// Draw image at context origin
image.draw(at: .zero)
// Get image
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
// Removes the current bitmap-based graphics context from the top of the stack
UIGraphicsEndImageContext()
// Return image
return finalImage
}
rect
為需要裁剪的區域,采用原圖的坐標系。angle
為需要旋轉的角度,單位是度,正值表示圖片順時針方向旋轉。具體實現的講解見注釋。
最后的圖片可能超出原圖區域,超出部分為透明。
轉載請注明出處:http://www.cnblogs.com/silence-cnblogs/p/6516593.html