裁剪图像中心

时间:2017-11-30 01:52:35

标签: ios swift uiimage

我想通过获取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
        }

2 个答案:

答案 0 :(得分:2)

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

prefetch

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

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

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)

答案 1 :(得分:1)

如果宽度大于高度:

使用全高:

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使用rects,它具有原点,高度和宽度。

相关问题