swift - 组合图像 SwiftUI

标签 swift swiftui uikit

我找到了一个关于组合两个图像以创建一个可以在此响应中共享和保存的新图像的答案:Stack response on how to combine two images swiftui (swift 5 answer by Glen) 。我对如何在代码中使用它感到困惑,因为我不熟悉 SwiftUI/UIKit 交叉。您能展示一个如何使用 UIImage 扩展来组合两个图像的示例吗?

extension UIImage {
  func mergeWith(topImage: UIImage) -> UIImage {
    let bottomImage = self

    UIGraphicsBeginImageContext(size)

    let areaSize = CGRect(x: 0, y: 0, width: bottomImage.size.width, height:    bottomImage.size.height)
    bottomImage.draw(in: areaSize)

    topImage.draw(in: areaSize, blendMode: .normal, alpha: 1.0)

    let mergedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return mergedImage
  }
}

最佳答案

引用Swift docs在这里。

Extensions add new functionality to an existing class, structure, enumeration, or protocol type.

您将使用如下扩展,

let image1 = UIImage(named: "yourimage1")
let image2 = UIImage(named: "yourimage2")
let finalImage = image1.mergeWith(image2)
//Use finalImage for sharing or saving..

关于swift - 组合图像 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64887200/

相关文章:

ios - 如何在 iOS 15 中删除节标题分隔符

swift - UILabel 在单词中间拆分(或如何获得正确的自动换行)

ios - 从选择器中获取选定的项目 | swift 用户界面

ios - performSegue(withIdentifier.......) 不工作

iphone - NSSearchPathForDirectoriesInDomains 麻烦(掉头发快)

iphone - 调整图像大小以适合比例

ios - 如何以编程方式从 Storyboard 中填充静态 UITableView?

swiftui - 几何读取器框架更改时未调用 onPreferenceChange

swiftui - 如何在 SwiftUI 中从父 View 更改子级 @State 属性值?

SwiftUI 多行文本背景颜色