gpt4 book ai didi

ios - 在 UIImage 周围添加透明空间

转载 作者:IT王子 更新时间:2023-10-29 07:53:29 24 4
gpt4 key购买 nike

假设我们有一个 600X400 像素的图像,我们希望最终得到一个 1000x1000 像素的新图像,其中包含中心的初始图像和周围的透明空间。我怎样才能在代码中实现这一点?

enter image description here

最佳答案

在 Swift 中,您可以编写 UIImage 的扩展,以绘制周围带有插图的图像。

swift 3:

import UIKit

extension UIImage {
func imageWithInsets(insets: UIEdgeInsets) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: self.size.width + insets.left + insets.right,
height: self.size.height + insets.top + insets.bottom), false, self.scale)
let _ = UIGraphicsGetCurrentContext()
let origin = CGPoint(x: insets.left, y: insets.top)
self.draw(at: origin)
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
}

旧答案:

import UIKit

extension UIImage {
func imageWithInsets(insets: UIEdgeInsets) -> UIImage {
UIGraphicsBeginImageContextWithOptions(
CGSizeMake(self.size.width + insets.left + insets.right,
self.size.height + insets.top + insets.bottom), false, self.scale)
let context = UIGraphicsGetCurrentContext()
let origin = CGPoint(x: insets.left, y: insets.top)
self.drawAtPoint(origin)
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
}

关于ios - 在 UIImage 周围添加透明空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20021478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com