這篇文章將為大家詳細講解有關iOS如何實現圖片裁剪 + 旋轉,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
裁剪和旋轉是可以連在一起執行的。先定位到需要裁剪的區域,然后以此區域的中心為軸,旋轉一定角度,最后獲取旋轉后此區域內的圖片??梢杂梦粓D(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為需要旋轉的角度,單位是度,正值表示圖片順時針方向旋轉。具體實現的講解見注釋。
最后的圖片可能超出原圖區域,超出部分為透明。
關于“iOS如何實現圖片裁剪 + 旋轉”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。