【问题标题】:How to position image view on top of a photo correctly using Swift如何使用 Swift 将图像视图正确定位在照片顶部
【发布时间】:2016-11-18 23:20:49
【问题描述】:

目前我可以保存顶部带有图像的照片,但是顶部图像不在预览视图中出现在屏幕上时的坐标处。

fileprivate func mergeUIViews( ) -> UIImage?
{
    let bottomImage = photo
    let topImage    = uiViewInstance.image

    let bottomImageHeight = bottomImage.size.height
    let bottomImageWidth  = bottomImage.size.width

    let topImageHeight = uiViewInstance.frame.height
    let topImageWidth  = uiViewInstance.frame.width
    let topImageOrigin = uiViewInstance.frame.origin

    let bottomImageSize = CGSize(width: bottomImageWidth, height: bottomImageHeight)
    let topImageSize = CGSize(width: topImageWidth, height: topImageHeight)

    // Merge images

    UIGraphicsBeginImageContextWithOptions(bottomImageSize, false, 0.0)

    bottomImage.draw(in: CGRect(origin: CGPoint.zero, size: bottomImageSize))
    topImage   .draw(in: CGRect(origin: topImageOrigin, size: topImageSize)) // Where I believe the problem exists
    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return newImage
}

【问题讨论】:

  • 您打印了uiViewInstance.frame.origin 吗?是你期待的CGPoint吗?
  • @Ryan 在情节提要中,我将顶部图像水平和垂直设置在中心进行测试。但是,一旦运行此代码并将合并的图像保存到照片库中,顶部图像就会出现在左上角,水平和垂直方向都有一点间距
  • 愚蠢的问题,但是您检查过 newImage 的样子吗?是否有可能它也有原点为 (0,0) 的顶部图像?
  • @dfd print(topImageOrigin) 导致点 (63.0,230.0) 但是在情节提要中,我将约束设置为水平和垂直居中(我认为这会在内部设置其 origin 属性?可能是? )。 topImage 在左上角显示的比例可能是原始图像的 1/5。
  • 好吧,这听起来更像是与布局有关的东西——无论是约束还是其他东西。两个想法 - 首先,newImage 是什么样的?如果它已损坏,那么您就知道问题所在(我想您已经看到了)。第二,你能提供更多的代码吗?特别是 - 但不限于 - 约束。

标签: ios swift merge draw photos


【解决方案1】:

有效的方法不是使用实际捕获的照片大小,而是将照片大小设置为视图控制器大小的视图。这导致整个屏幕的所需输出显示合并的照片以及重叠图像原点的正确点。

fileprivate func mergeUIViews( ) -> UIImage?
{
    let bottomImage = photo
    let topImage    = uiViewInstance.image

    let bottomImageSize = self.view.frame.size

    let topImageHeight = uiViewInstance.frame.height
    let topImageWidth  = uiViewInstance.frame.width
    let topImageOrigin = uiViewInstance.frame.origin
    let topImageSize   = uiViewInstance.frame.size

    // Merge images

    UIGraphicsBeginImageContextWithOptions(bottomImageSize, false, 0.0)

    bottomImage.draw(in: CGRect(origin: CGPoint.zero, size: bottomImageSize))
    topImage   .draw(in: CGRect(origin: topImageOrigin, size: topImageSize)) // Where I believe the problem exists
    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return newImage
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多