這篇文章將為大家詳細(xì)講解有關(guān)iOS如何實(shí)現(xiàn)圖片裁剪 + 旋轉(zhuǎn),小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
裁剪和旋轉(zhuǎn)是可以連在一起執(zhí)行的。先定位到需要裁剪的區(qū)域,然后以此區(qū)域的中心為軸,旋轉(zhuǎn)一定角度,最后獲取旋轉(zhuǎn)后此區(qū)域內(nèi)的圖片??梢杂梦粓D(Bitmap)繪制實(shí)現(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ū)域,采用原圖的坐標(biāo)系。angle為需要旋轉(zhuǎn)的角度,單位是度,正值表示圖片順時(shí)針方向旋轉(zhuǎn)。具體實(shí)現(xiàn)的講解見注釋。
最后的圖片可能超出原圖區(qū)域,超出部分為透明。
關(guān)于“iOS如何實(shí)現(xiàn)圖片裁剪 + 旋轉(zhuǎn)”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站www.cdcxhl.com,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。