2017-06-08 81 views
0

我得到1920x1080分辨率的图像。我试图将它们裁剪到中心广场区域(即中心的1080x1080平方米)。决议可能在未来发生变化。这样可以裁剪图像吗?我曾尝试过几个贴在SO上的东西,但如果我尝试裁剪中心,我总是会得到一个660x1080的图像。这是一幅描绘我想要达到的图像。 pic裁剪UIImage到中心广场

基本上红色是原始的,绿色是我想要的,黄色只是显示mixX和midY线。

我试过的代码。

func imageByCroppingImage(image: UIImage, toSize size: CGSize) -> UIImage{ 
    let newCropWidth: CGFloat? 
    let newCropHeight: CGFloat? 

    if image.size.width < image.size.height { 
     if image.size.width < size.width { 
      newCropWidth = size.width 
     } else { 
      newCropWidth = image.size.width 
     } 
     newCropHeight = (newCropWidth! * size.height)/size.width 
    } else { 
     if image.size.height < size.height { 
      newCropHeight = size.height 
     } else { 
      newCropHeight = image.size.height 
     } 
     newCropWidth = (newCropHeight! * size.width)/size.height 
    } 

    let x = image.size.width/2.0 - newCropWidth!/2.0 
    let y = image.size.height/2.0 - newCropHeight!/2.0 

    let cropRect = CGRect(x: x, y: y, width: newCropWidth!, height: newCropHeight!) 
    let imageRef = image.cgImage!.cropping(to: cropRect) 

    let cropped = UIImage(cgImage: imageRef!, scale: 1.0, orientation: .right) 
    return cropped 
} 

然后我通过该方法CGSize(1080,1080)。我得到一个660,1080的图像。有什么想法?

意图是裁剪图像,而不是只显示它居中。

+0

尝试imageView.center&也分享 – Spynet

+0

你是不是想代码从字面上裁剪原始图像还是只呈现它平方? –

+0

@LeoDabus试图裁剪它。 – Minebomber

回答

2

你可以用我在这个answer使用,而线同样的方法UIBezierPath(ovalIn: breadthRect).addClip()


extension UIImage { 
    var isPortrait: Bool { return size.height > size.width } 
    var isLandscape: Bool { return size.width > size.height } 
    var breadth:  CGFloat { return min(size.width, size.height) } 
    var breadthSize: CGSize { return CGSize(width: breadth, height: breadth) } 
    var breadthRect: CGRect { return CGRect(origin: .zero, size: breadthSize) } 
    var squared: UIImage? { 
     UIGraphicsBeginImageContextWithOptions(breadthSize, false, scale) 
     defer { UIGraphicsEndImageContext() } 
     guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(x: isLandscape ? floor((size.width - size.height)/2) : 0, y: isPortrait ? floor((size.height - size.width)/2) : 0), size: breadthSize)) else { return nil } 
     UIImage(cgImage: cgImage).draw(in: breadthRect) 
     return UIGraphicsGetImageFromCurrentImageContext() 
    } 
} 

let imageURL = URL(string: "https://www.sample.com/yourImage.jpg")! 
let image = UIImage(data: try! Data(contentsOf: imageURL))! 
let squared = image.squared