2017-06-08 118 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