温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

iOS如何实现图片裁剪 + 旋转

发布时间:2021-07-09 09:18:32 来源:亿速云 阅读:185 作者:小新 栏目:移动开发

这篇文章将为大家详细讲解有关iOS如何实现图片裁剪 + 旋转,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

裁剪和旋转是可以连在一起执行的。先定位到需要裁剪的区域,然后以此区域的中心为轴,旋转一定角度,最后获取旋转后此区域内的图片。可以用位图(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如何实现图片裁剪 + 旋转”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

ios
AI