2016-09-23 5 views
14

Цель: Обрезка UIImage (который начинается с scale свойство 2.0)Как обрезать UIImage, не теряя при этом свойство масштаба?

я выполнить следующий код:

let croppedCGImage = originalUIImage.cgImage!.cropping(to: cropRect) 
let croppedUIImage = UIImage(cgImage: croppedCGImage!) 

Этот код работает, однако результат, croppedUIImage, имеет неправильную scale свойство 1,0.


Я попытался указав scale при создании конечного изображения:

let croppedUIImage = UIImage(cgImage: croppedCGImage!, scale: 2.0, orientation: .up) 

Это дает правильный масштаб, но он режет size размеры в два раза неправильно.


Что мне здесь делать?

(* Примечание: scale свойство на UIImage важно, потому что я потом сохранить изображение с UIImagePNGRepresentation(_ image: UIImage), на которую влияет на scale собственности)



Edit:

я получил для работы. К сожалению, это просто существенно медленнее, чем функция обрезки CGImage.

extension UIImage { 
    func cropping(to rect: CGRect) -> UIImage { 
     UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale) 

     self.draw(in: CGRect(x: -rect.origin.x, y: -rect.origin.y, width: self.size.width, height: self.size.height)) 

     let croppedImage = UIGraphicsGetImageFromCurrentImageContext()! 
     UIGraphicsEndImageContext() 

     return croppedImage 
    } 
} 

ответ

6

Попробуйте это:

extension UIImage { 
    func imageByCropToRect(rect:CGRect, scale:Bool) -> UIImage { 

     var rect = rect 
     var scaleFactor: CGFloat = 1.0 
     if scale { 
      scaleFactor = self.scale 
      rect.origin.x *= scaleFactor 
      rect.origin.y *= scaleFactor 
      rect.size.width *= scaleFactor 
      rect.size.height *= scaleFactor 
     } 

     var image: UIImage? = nil; 
     if rect.size.width > 0 && rect.size.height > 0 { 
      let imageRef = self.cgImage!.cropping(to: rect) 
      image = UIImage(cgImage: imageRef!, scale: scaleFactor, orientation: self.imageOrientation) 
     } 

     return image! 
    } 
} 
4

Используйте этот Extension: -

extension UIImage { 

    func cropping(to quality: CGInterpolationQuality, rect: CGRect) -> UIImage { 
     UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale) 

     let context = UIGraphicsGetCurrentContext()! as CGContext 
     context.interpolationQuality = quality 

     let drawRect : CGRect = CGRect(x: -rect.origin.x, y: -rect.origin.y, width: self.size.width, height: self.size.height) 

     context.clip(to: CGRect(x:0, y:0, width: rect.size.width, height: rect.size.height)) 

     self.draw(in: drawRect) 

     let croppedImage = UIGraphicsGetImageFromCurrentImageContext()! 
     UIGraphicsEndImageContext() 

     return croppedImage 
    } 
} 
+0

, как вы ожидаете, этот код будет обрезать изображение от положения и размера прямоугольника в ?? его не работает для меня –

3

Я использую ImageHelper Pod для прошивки и tvOS и он прекрасно работает и, возможно, также подходит твои нужды.

Это приносит много UIImage расширения, такие как:

Обрезка и изменение размера

// Crops an image to a new rect 
func crop(bounds: CGRect) -> UIImage? 

// Crops an image to a centered square 
func cropToSquare() -> UIImage? { 

// Resizes an image 
func resize(size:CGSize, contentMode: UIImageContentMode = .ScaleToFill) -> UIImage? 

экрана Плотность

// To create an image that is Retina aware, use the screen scale as a multiplier for your size. You should also use this technique for padding or borders. 
let width = 140 * UIScreen.mainScreen().scale 
let height = 140 * UIScreen.mainScreen().scale 
let image = UIImage(named: "myImage")?.resize(CGSize(width: width, height: height)) 

также Основные вещи, как: эффекты изображения

// Applies a light blur effect to the image 
func applyLightEffect() -> UIImage? 
// Applies a extra light blur effect to the image 
func applyExtraLightEffect() -> UIImage? 
// Applies a dark blur effect to the image 
func applyDarkEffect() -> UIImage? 
// Applies a color tint to an image 
func applyTintEffect(tintColor: UIColor) -> UIImage? 
// Applies a blur to an image based on the specified radius, tint color saturation and mask image 
func applyBlur(blurRadius:CGFloat, tintColor:UIColor?, saturationDeltaFactor:CGFloat, maskImage:UIImage? = nil) -> UIImage? 
1
-(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect 
{ 

    CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect); 
    UIImage *croppedImage = [UIImage imageWithCGImage:subImage]; 
    CGImageRelease(subImage); 
    return croppedImage; 
} 

вызова

UIImage *imageSample=image; 
    CGRect rectMake1=CGRectMake(0, 0,imageSample.size.width*1/4, imageSample.size.height); 
    UIImage *img1=[[JRGlobal sharedInstance] getNeedImageFrom:imageSample cropRect:rectMake1]; 
Смежные вопросы