之前分別介紹了圖片裁剪和圖片旋轉(zhuǎn)方法
裁剪和旋轉(zhuǎn)是可以連在一起執(zhí)行的。先定位到需要裁剪的區(qū)域,然后以此區(qū)域的中心為軸,旋轉(zhuǎn)一定角度,最后獲取旋轉(zhuǎn)后此區(qū)域內(nèi)的圖片??梢杂梦粓D(Bitmap)繪制實現(xiàn)
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為需要裁剪的區(qū)域,采用原圖的坐標系。angle為需要旋轉(zhuǎn)的角度,單位是度,正值表示圖片順時針方向旋轉(zhuǎn)。具體實現(xiàn)的講解見注釋。
最后的圖片可能超出原圖區(qū)域,超出部分為透明。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持VEVB武林網(wǎng)!
新聞熱點
疑難解答
圖片精選