【问题标题】:Crop Image Center [duplicate]裁剪图像中心 [重复]
【发布时间】:2017-11-30 01:52:35
【问题描述】:

我想通过获取 x1、x2、y1、y2 的值​​将纵向/横向图像裁剪为中心完美方形图像。怎么做?

let x = pickedImage.size.width
let y = pickedImage.size.height

        // Portrait image
        if(pickedImage.size.width < pickedImage.size.height){
            //crop image and get value of x1,x2,y1,y2
        }
        //Landscape image
        else if(pickedImage.size.width > pickedImage.size.height) {
           //crop image and get value of x1,x2,y1,y2
        }

【问题讨论】:

    标签: ios swift uiimage


    【解决方案1】:

    有一个简单的公式。无需检查方向。

    let width = image.size.width
    let height = image.size.height
    let size = min(width, height)
    let x = (width - size) / 2
    let y = (height - size) / 2
    let frame = CGRect(x: x, y: y, width: size, height: size)
    

    这将使中心正方形占据整个宽度或高度,以较小者为准。

    或者如果你想要你的 (x1, y1) - 左上角,(x2, y2) - 右下角:

    let width = image.size.width
    let height = image.size.height
    let size = min(width, height)
    let x1 = (width - size) / 2
    let y1 = (height - size) / 2
    let x2 = x1 + size
    let y2 = y1 + size
    

    【讨论】:

    • 这比担心哪一边更长更干净。使用 min 可以避免使用 if 语句。这个答案比“重复问题”链接中的答案要好。 (已投票)。
    • @DuncanC 这个我们不用管它是纵向还是横向已经对了?
    • @NurII 这个答案适用于两种类型的图像。
    • @rmaddy 它对我有用,谢谢 :)
    【解决方案2】:

    如果宽度大于高度:

    使用全高:

    y1 = 0
    y2 = height
    

    将 x 位置插入额外宽度的一半

    x1 = (width - height)/2
    x2 = height + x1
    

    如果高度大于宽度:

    使用全宽

    x1 = 0
    x2 = width
    

    将 y 位置插入额外高度的一半

    y1 = (height - width) / 2
    y2 = width + y1
    

    但是你为什么要 x1、x2、y1、y2? iOS 和 Mac OS 使用矩形,它有一个原点、一个高度和一个宽度。

    【讨论】:

      猜你喜欢
      • 2017-12-29
      • 2014-05-26
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多