在 ImageView 中添加基于图像的新框架,用于照片编辑应用程序

Adding New Frame based on Image inside ImageView for PhotoEditing App

我正在开发照片编辑应用程序,我需要在图像上添加框架基本上我已经使用了另一个 UIImageView 与我原来的 UIImageView 相同的框架,并简单地添加了 png 图像。现在的问题是我需要基于图像视图内框架的高度和宽度的框架。

如上图所示,我的框架出现在整个 UIImageView 中,但我在 Imageview 中的图像是风景,所以如果我在 Imageview 中的图像是风景,那么我需要风景框架,如果图像是肖像,那么我需要肖像框架。我如何实现这一目标?

我使用了 2 个具有相同高度宽度的图像视图,一个是原始图像视图,另一个是框架图像视图现在我已经使用以下代码应用图像

StoryBoard 中的图片输出

@IBOutlet var imgFrame: UIImageView!

正在将框架应用于 ImageView

                imgFrame.isHidden = false
                imgFrame.image = #imageLiteral(resourceName: "Frame-Style-1.png")

假设这些是您的 mainImageView 和图片(横向)的价值:

mainImageView.frame.size
▿ (500.0, 500.0)
  - width : 500.0
  - height : 500.0

mainImageView.image?.size
▿ Optional<CGSize>
  ▿ some : (1440.0, 800.0)
    - width : 1440.0
    - height : 800.0

你知道宽度是500,高度可以这样计算: frame.width / image.width * image.height

我认为你需要两件事。

保持框架 UIImageView 的大小与源 UIImageView 相同。

要配置它,您必须将框架图像视图的顶部、底部、前导和尾部 锚点与源图像视图的相应锚点对齐。

将源 UIImageView 的大小调整为图像的大小。

UIImageView 尺寸调整为 UIImage 尺寸最简单的方法是使用 宽高比约束 。更重要的是,我将 UIImageViewcontent mode 配置为 scale to fill

let image = UIImage(named: "portrait")!
let aspectRatio = image.size.height / image.size.width

let aspectRatioConstraint = NSLayoutConstraint(item: userImageView,attribute: .height,relatedBy: .equal,toItem: userImageView,attribute: .width,multiplier: aspectRatio,constant: 0)

userImageView.image = image
userImageView.addConstraint(aspectRatioConstraint)

frameImageView.image = UIImage(named: "landscape-frame")

您还必须将 source UIImageView 定位在视图控制器中,但我将其留给您。 这是我使用此代码获得的示例结果。

这是 GitHub

上示例项目的 link

使 innerImageview.scaleAspectFit 一样显示图像而没有 space:

func set(image: UIImage, to imageView: UIImageView) {
    // 1. find sizeScale
    let sizeScaleX = imgFrame.frame.width / image.size.width
    let sizeScaleY = imgFrame.frame.height / image.size.height
    let sizeScale = sizeScaleX > sizeScaleY ? sizeScaleX : sizeScaleY

    // 2. change imageView's frame
    imageView.frame.size = CGSize(width: image.size.width*sizeScale, height: image.size.height*sizeScale)

    // 3. center imageView
    imageView.frame.origin.x = (imgFrame.frame.width-imageView.frame.width)/2
    imageView.frame.origin.y = (imgFrame.frame.height-imageView.frame.height)/2
}

// image is the image what you got (from library/camera or anywhere)
// 1. set image to imgFrame which contain space
imgFrame.image = image
// 2. generate a new image without space
var innerImageView = UIImageView()
set(image: image, to: innerImageView)
// 3. add frame on image
imgFrame.addSubview(innerImageView)