首页 > 解决方案 > 在 UIImage 上添加 UIView - swift - 以编程方式

问题描述

我有一个大小为 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 上使用它我得到了放大的视图,你知道我做错了什么吗?

标签: swiftuiviewuigraphicscontext

解决方案


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

希望这将简化和帮助。


推荐阅读