3

I want to crop a portrait / landscape image to a centre perfect square image by getting the value of x1, x2, y1, y2. How to do it?

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
        }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Nur II
  • 173
  • 1
  • 2
  • 16

2 Answers2

3

There's a simple formula. No need to check the orientation.

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)

This will give the center square taking up the full width or height, whichever is smaller.

Or if you want your (x1, y1) - upper left, (x2, y2) - lower right:

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
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • This is better and cleaner than worrying about which side is longer. Using min allows you to avoid an if statement. This answer is better than the one linked in the "duplicate question" link. (Voted). – Duncan C Nov 30 '17 at 11:02
  • @DuncanC For this we no need to care about whether it is portrait or landscape image already right? – Nur II Dec 04 '17 at 05:17
  • @NurII This answer works for both types of images. – rmaddy Dec 04 '17 at 06:10
  • @rmaddy it work for me, thanks :) – Nur II Dec 04 '17 at 08:47
1

If the width is greater than the height:

Use the full height:

y1 = 0
y2 = height

Inset the x position by half the extra width

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

If the height is greater than the width:

Use the full width

x1 = 0
x2 = width

Inset the y position by half the extra height

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

But why do you want x1, x2, y1, y2? iOS and Mac OS use rects, which have an origin, a height, and a width.

Duncan C
  • 128,072
  • 22
  • 173
  • 272