2016-10-11 93 views
6

我正在使用自定義相機應用程序。事情運作良好。以編程方式從底部裁剪圖像

但我從底部裁剪圖像時遇到了問題。即裁剪後的圖像與原始圖像具有完全相同的寬度,但高度將爲原始圖像的1/3,並且其必須從底部開始。

For Example Like this is the full image I need the red part only

回答

17
夫特

3溶液:

func cropBottomImage(image: UIImage) -> UIImage { 
    let height = CGFloat(image.size.height/3) 
    let rect = CGRect(x: 0, y: image.size.height - height, width: image.size.width, height: height) 
    return cropImage(image: image, toRect: rect) 
} 

用於與矩形裁剪Helper方法:

func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage{ 
    let imageRef:CGImage = image.cgImage!.cropping(to: rect)! 
    let croppedImage:UIImage = UIImage(cgImage:imageRef) 
    return croppedImage 
} 
0

方法:

func croppIngimage(ImageCrop:UIImage, toRect rect:CGRect) -> UIImage{ 

    var imageRef:CGImageRef = CGImageCreateWithImageInRect(imageToCrop.CGImage, rect) 
    var croppedimage:UIImage = UIImage(CGImage:imageRef) 
    return croppedimage 
} 

呼叫:

var ImageCrop:UIImage = UIImage(named:"image.png") 
+0

假設我有一個圖像大小2448×3264我想那部分,即紅色的一個。什麼是toRect參數? – BornShell

+0

看到這個:http://stackoverflow.com/questions/37946990/cgrectmake-cgpointmake-cgsizemake-cgrectzero-cgpointzero-is-unavailable-in –

7

這幾乎是Alexburtnik的回答

只是提一提,UIImage.size是邏輯大小(以 「點」)

然而,CGImage.cropping()使用的實際尺寸(在「像素」中)

因此,如果您使用帶有@ 2x或@ 3x修改器的圖像,則會發現 裁剪實際上只是期望的一半或三分之一。

所以當你裁剪,你可以考慮先RECT通過圖像的「尺度」屬性相乘,如下所示:

func cropImage(image:UIImage, toRect rect:CGRect) -> UIImage? { 
    var rect = rect 
    rect.size.width = rect.width * image.scale 
    rect.size.height = rect.height * image.scale 

    guard let imageRef = image.cgImage?.cropping(to: rect) else { 
     return nil 
    } 

    let croppedImage = UIImage(cgImage:imageRef) 
    return croppedImage 
} 
0

作爲擴展的UIImage:

import UIKit 

extension UIImage { 
    func crop(to rect: CGRect) -> UIImage? { 
     // Modify the rect based on the scale of the image 
     var rect = rect 
     rect.size.width = rect.size.width * self.scale 
     rect.size.height = rect.size.height * self.scale 

     // Crop the image 
     guard let imageRef = self.cgImage?.cropping(to: rect) else { 
      return nil 
     } 

     return UIImage(cgImage: imageRef) 
    } 
} 

用法:

let myImage = UIImage(named:"myImage.png")  
let croppedRect = CGRect(x: 0, y: 0, width: newWidth, height: newHeight) 
let croppedImage = myImage.crop(to: croppedRect)