在 UIImage 上添加 UIView - swift - 以编程方式

Posted

技术标签:

【中文标题】在 UIImage 上添加 UIView - swift - 以编程方式【英文标题】:Add UIView over UIImage - swift - programmatically 【发布时间】:2020-10-08 11:11:08 【问题描述】:

我有一个大小为 1080x1920 的 UIImage 和一个大小为 375x812 的 UIView。 我想放大视图并将其绘制在中心的 UIImage 上,以这种方式:

初始阶段:

第二阶段:

这是我实现的代码,用于通过 UIImage 放大 UIView:

let proportionalWidthUpperView = (inImage.size.height * self.view.frame.size.width)/self.view.frame.size.height
    let differenceWidth = inImage.size.width - proportionalWidthUpperView
    
    
    UIGraphicsBeginImageContext(inImage.size)
    let rect = CGRect(x: differenceWidth/2, y: 0, width: inImage.size.width-(differenceWidth), height: inImage.size.height)
    inImage.draw(in: CGRect(x: 0, y: 0, width: inImage.size.width, height: inImage.size.height))
    imageFromUpperView?.draw(in: rect)
    let result = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return result!

放大视图使其与 UIImage 高度匹配,我检索宽度的差异并将其添加到矩形的左侧和右侧。

此方法在 iPhone 上完美运行,但在具有更大视图框架的 iPad 上使用它,我得到了放大的视图,你知道我做错了什么吗?

【问题讨论】:

【参考方案1】:

尝试将 UIView 作为子视图添加到 UIImageView 中,您可以应用转换和缩放并保留添加的 UIView 的框架。

希望这会简化并有所帮助。

【讨论】:

以上是关于在 UIImage 上添加 UIView - swift - 以编程方式的主要内容,如果未能解决你的问题,请参考以下文章