簡體   English   中英

裁剪 UIImage 的中心正方形

[英]Cropping center square of UIImage

所以這就是我到目前為止所做的。 我正在使用從相機捕獲的 UIImage 並且可以在橫向時裁剪中心正方形。 出於某種原因,這不會按預期轉換為縱向模式。 我將發布我的代碼和日志僅供參考。

代碼:

CGRect squareRect = CGRectMake(offsetX, offsetY, newWidth, newHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], squareRect);
image = [UIImage imageWithCGImage:imageRef scale:1 orientation:image.imageOrientation];

縱向結果(非方形):

original image size: {1536, 2048}, with orientation: 3
squareRect: {{0, 256}, {1536, 1536}}
new image size: {1280, 1536}, with orientation: 3 <--- not expected

景觀結果(正方形):

original image size: {2048, 1536}, with orientation: 1
squareRect: {{256, 0}, {1536, 1536}}
new image size: {1536, 1536}, with orientation: 1

這是 CGImageCreateWithImageInRect() 中的錯誤還是我在這里遺漏了什么?

我認為這將是完美的解決方案!
根據toSize大小裁剪圖像不是一個好主意。 當圖像分辨率(尺寸)非常大時,它看起來會很奇怪。
以下代碼將根據toSize比例裁剪圖像。
改進了@BlackRider的回答。

- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
    double newCropWidth, newCropHeight;

    //=== To crop more efficently =====//
    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;
    }
    //==============================//

    double x = image.size.width/2.0 - newCropWidth/2.0;
    double y = image.size.height/2.0 - newCropHeight/2.0;

    CGRect cropRect = CGRectMake(x, y, newCropWidth, newCropHeight);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return cropped;
}

這適用於不同的方向。 縱向和橫向都可以正常工作。

- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
    // not equivalent to image.size (which depends on the imageOrientation)!
    double refWidth = CGImageGetWidth(image.CGImage);
    double refHeight = CGImageGetHeight(image.CGImage);

    double x = (refWidth - size.width) / 2.0;
    double y = (refHeight - size.height) / 2.0;

    CGRect cropRect = CGRectMake(x, y, size.height, size.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:self.imageOrientation];
    CGImageRelease(imageRef);

    return cropped;
}

根據 Elmundo 的檢查答案和 Imbrue 的 swift 版本,這里是自動計算圖像中心大小(考慮方向)並考慮錯誤的相同解決方案:

func cropImageToSquare(image: UIImage) -> UIImage? {
    var imageHeight = image.size.height
    var imageWidth = image.size.width

    if imageHeight > imageWidth {
        imageHeight = imageWidth
    }
    else {
        imageWidth = imageHeight
    }

    let size = CGSize(width: imageWidth, height: imageHeight)

    let refWidth : CGFloat = CGFloat(CGImageGetWidth(image.CGImage))
    let refHeight : CGFloat = CGFloat(CGImageGetHeight(image.CGImage))

    let x = (refWidth - size.width) / 2
    let y = (refHeight - size.height) / 2

    let cropRect = CGRectMake(x, y, size.height, size.width)
    if let imageRef = CGImageCreateWithImageInRect(image.CGImage, cropRect) {
        return UIImage(CGImage: imageRef, scale: 0, orientation: image.imageOrientation)
    }

   return nil
}

斯威夫特 3版本

func cropImageToSquare(image: UIImage) -> UIImage? {
    var imageHeight = image.size.height
    var imageWidth = image.size.width

    if imageHeight > imageWidth {
        imageHeight = imageWidth
    }
    else {
        imageWidth = imageHeight
    }

    let size = CGSize(width: imageWidth, height: imageHeight)

    let refWidth : CGFloat = CGFloat(image.cgImage!.width)
    let refHeight : CGFloat = CGFloat(image.cgImage!.height)

    let x = (refWidth - size.width) / 2
    let y = (refHeight - size.height) / 2

    let cropRect = CGRect(x: x, y: y, width: size.height, height: size.width)
    if let imageRef = image.cgImage!.cropping(to: cropRect) {
        return UIImage(cgImage: imageRef, scale: 0, orientation: image.imageOrientation)
    }

    return nil
}

嘗試這樣的事情:

- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
    double x = (image.size.width - size.width) / 2.0;
    double y = (image.size.height - size.height) / 2.0;

    CGRect cropRect = CGRectMake(x, y, size.height, size.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return cropped;
}

如您所見,我沒有在調用UIImage imageWithCGImage:指定方向。 我想知道這是否是您代碼中的問題。

檢查的解決方案有 swift 版本:

private func imageByCroppingImage(image : UIImage, size : CGSize) -> UIImage{
        var refWidth : CGFloat = CGFloat(CGImageGetWidth(image.CGImage))
        var refHeight : CGFloat = CGFloat(CGImageGetHeight(image.CGImage))

        var x = (refWidth - size.width) / 2
        var y = (refHeight - size.height) / 2

        let cropRect = CGRectMake(x, y, size.height, size.width)
        let imageRef = CGImageCreateWithImageInRect(image.CGImage, cropRect)

        let cropped : UIImage = UIImage(CGImage: imageRef, scale: 0, orientation: image.imageOrientation)!


        return cropped
    }

從@Elmundo 的回答中改進

+(UIImage *)getCenterMaxSquareImageByCroppingImage:(UIImage *)image withOrientation:(UIImageOrientation)imageOrientation

{
    CGSize centerSquareSize;
    double oriImgWid = CGImageGetWidth(image.CGImage);
    double oriImgHgt = CGImageGetHeight(image.CGImage);
    NSLog(@"oriImgWid==[%.1f], oriImgHgt==[%.1f]", oriImgWid, oriImgHgt);
    if(oriImgHgt <= oriImgWid) {
        centerSquareSize.width = oriImgHgt;
        centerSquareSize.height = oriImgHgt;
    }else {
        centerSquareSize.width = oriImgWid;
        centerSquareSize.height = oriImgWid;
    }

    NSLog(@"squareWid==[%.1f], squareHgt==[%.1f]", centerSquareSize.width, centerSquareSize.height);

    double x = (oriImgWid - centerSquareSize.width) / 2.0;
    double y = (oriImgHgt - centerSquareSize.height) / 2.0;
    NSLog(@"x==[%.1f], x==[%.1f]", x, y);

    CGRect cropRect = CGRectMake(x, y, centerSquareSize.height, centerSquareSize.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:imageOrientation];
    CGImageRelease(imageRef);


    return cropped;
}

這是一個老問題,但沒有一個答案是真正正確的(即使是公認的答案)。 需要理解的重要一點是UIImageOrientation ( image.imageOrientation ) 實際上是正確的,但它對UP的定義和我們對UP的定義不同。 對我們來說, UP是設備的頂部(電源按鈕所在的位置)。 對於UIImageOrientation向上是音量控制按鈕的對面 因此,如果設備在音量控制降低的情況下UIImageOrientationUp ,則為UIImageOrientationUp 如果您以縱向模式(按下主頁按鈕) UIImageOrientationLeft ,這是UIImageOrientationLeft

所以你可以計算縱向的中心,然后你可以對圖像應用以下變換,使裁剪在正確的位置。

- (UIImage *)cropImage:(UIImage*)image toRect:(CGRect)rect {
    CGFloat (^rad)(CGFloat) = ^CGFloat(CGFloat deg) {
        return deg / 180.0f * (CGFloat) M_PI;
    };

    // determine the orientation of the image and apply a transformation to the crop rectangle to shift it to the correct position
    CGAffineTransform rectTransform;
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -image.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -image.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -image.size.width, -image.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };

    // adjust the transformation scale based on the image scale
    rectTransform = CGAffineTransformScale(rectTransform, image.scale, image.scale);

    // apply the transformation to the rect to create a new, shifted rect
    CGRect transformedCropSquare = CGRectApplyAffineTransform(rect, rectTransform);
    // use the rect to crop the image
    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, transformedCropSquare);
    // create a new UIImage and set the scale and orientation appropriately
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation];
    // memory cleanup
    CGImageRelease(imageRef);

    return result;
}

此代碼移動裁剪方塊,使其處於正確的相對位置。

Swift 2 使用 UIImage 擴展

extension UIImage
{    
    func imageByCroppingImage(size : CGSize) -> UIImage
    {
        let refWidth : CGFloat = CGFloat(CGImageGetWidth(self.CGImage))
        let refHeight : CGFloat = CGFloat(CGImageGetHeight(self.CGImage))

        let x = (refWidth - size.width) / 2
        let y = (refHeight - size.height) / 2

        let cropRect = CGRectMake(x, y, size.width, size.height)
        let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropRect)

        let cropped : UIImage = UIImage(CGImage: imageRef!, scale: 0, orientation: self.imageOrientation)


        return cropped
    }
}

斯威夫特 3

    let refWidth : CGFloat = CGFloat(image.cgImage!.width)
    let refHeight : CGFloat = CGFloat(image.cgImage!.height)

    let x = (refWidth - size.width) / 2
    let y = (refHeight - size.height) / 2

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

    let cropped : UIImage = UIImage(cgImage: imageRef!, scale: 0, orientation: image.imageOrientation)


    return cropped

這是基於@Alonzo's Swift 3 answer 以上,代碼經過簡化和精簡,使其更易於理解和簡潔。 如果圖像已經是方形的,它也會退出。

extension UIImage {
    func square() -> UIImage? {
        if size.width == size.height {
            return self
        }

        let cropWidth = min(size.width, size.height)

        let cropRect = CGRect(
            x: (size.width - cropWidth) * scale / 2.0,
            y: (size.height - cropWidth) * scale / 2.0,
            width: cropWidth * scale,
            height: cropWidth * scale
        )

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

        return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
    }
}

從 UIImageView 獲得幫助怎么樣

+ (UIImage *)laodSquareImage:(UIImage *)image withDiameter:(CGFloat)diameter  
{
    CGRect frame = CGRectMake(0.0f, 0.0f, diameter, diameter);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    imageView.image = image;
    CALayer *layer = imageView.layer;


    layer.masksToBounds = YES;
    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size,NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [layer renderInContext:context];


    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return roundedImage;
}

您還可以通過添加一條線來制作圖像圓圈。

layer.cornerRadius =MAX( imageView.frame.size.height,imageView.frame.size.width)/2;

已經有很多解決方案,但我想發布我的:

  extension UIImage {

    var cgImageWidth: Int { return cgImage?.width ?? 0 }
    var cgImageheight: Int { return cgImage?.height ?? 0 }
    var blance: CGFloat { return min(size.width, size.height)}
    var blanceSize: CGSize { return CGSize(width: blance, height: blance) }
    var blanceRect: CGRect { return CGRect(origin: .zero, size: blanceSize) }

    var roundedImage: UIImage? {
        UIGraphicsBeginImageContextWithOptions(blanceSize, false, scale)
        defer { UIGraphicsEndImageContext() }
        guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(x: max(0, CGFloat(cgImageWidth) - blance)/2.0, y: max(0, CGFloat(cgImageheight) - blance)/2.0), size: blanceSize)) else { return nil }
        UIBezierPath(ovalIn: blanceRect).addClip()

        UIImage(cgImage: cgImage, scale: 1.0, orientation: self.imageOrientation).draw(in: blanceRect)
        return UIGraphicsGetImageFromCurrentImageContext()
    }

}

沙馬林:

UIImage ImageByCroppingImage(UIImage image, CGSize size)
{
    double newCropWidth, newCropHeight;

    if (image.Size.Width < image.Size.Height)
    {
        newCropWidth = image.Size.Width < size.Width ? size.Width : image.Size.Width;
        newCropHeight = (newCropWidth * size.Height) / size.Width;
    }
    else
    {
        newCropHeight = image.Size.Height < size.Height ? size.Height : image.Size.Height;
        newCropWidth = (newCropHeight * size.Width) / size.Height;
    }

    double x = image.Size.Width / 2.0 - newCropWidth / 2.0;
    double y = image.Size.Height / 2.0 - newCropHeight / 2.0;

    CGRect cropRect = new CGRect(x, y, newCropWidth, newCropHeight);
    var imageRef = image.CGImage.WithImageInRect(cropRect);

    var cropped = new UIImage(imageRef);

    return cropped;
}

Swift 5 最干凈的版本。

func cropImage() -> UIImage? {
    let size = min(self.size.width, self.size.height)
    UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), true, 1.0)
    defer { UIGraphicsEndImageContext() }
    self.draw(in: CGRect(x: (size - self.size.width) / 2.0,
                          y: (size - self.size.height) / 2.0,
                          width: self.size.width,
                          height: self.size.height))
    return UIGraphicsGetImageFromCurrentImageContext()
}

斯威夫特 5

extension UIImage {

    var squared: UIImage? {
        guard let cgImage = cgImage else {
            return nil
        }

        let length = min(cgImage.width, cgImage.height)

        let x = cgImage.width / 2 - length / 2
        let y = cgImage.height / 2 - length / 2
        let cropRect = CGRect(x: x, y: y, width: length, height: length)

        guard let croppedCGImage = cgImage.cropping(to: cropRect) else {
            return nil
        }

        return UIImage(cgImage: croppedCGImage, scale: scale, orientation: imageOrientation)
    }
}

基於 Swift 2 擴展的解決方案。 由@Geoffrey 和@Nirav Dangi 即興創作。 請注意,當 newCropWidth 和 newCropHeight 小於給定的寬度或高度時,我們將它們設置為圖像的寬度或高度。

extension UIImage {
    func imageByCroppingImage(size: CGSize) -> UIImage {
        let newCropWidth, newCropHeight : CGFloat;

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

        let x = self.size.width / 2 - newCropWidth / 2;
        let y = self.size.height / 2 - newCropHeight / 2;

        let cropRect = CGRectMake(x, y, newCropWidth, newCropHeight);
        let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropRect);

        let croppedImage : UIImage = UIImage(CGImage: imageRef!, scale: 0, orientation: self.imageOrientation);

        return croppedImage;
    }
}

我正在處理以下問題

    extension UIImage {

    var cgImageWidth: Int { return cgImage?.width ?? 0 }
    var cgImageheight: Int { return cgImage?.height ?? 0 }
    var blance: CGFloat { return min(size.width, size.height)}
    var blanceSize: CGSize { return CGSize(width: blance, height: blance) }
    var blanceRect: CGRect { return CGRect(origin: .zero, size: blanceSize) }

    var roundedImage: UIImage? {
        UIGraphicsBeginImageContextWithOptions(blanceSize, false, scale)
        defer { UIGraphicsEndImageContext() }
        guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(x: max(0, CGFloat(cgImageWidth) - blance)/2.0, y: max(0, CGFloat(cgImageheight) - blance)/2.0), size: blanceSize)) else { return nil }
        UIBezierPath(ovalIn: blanceRect).addClip()

        UIImage(cgImage: cgImage, scale: 1.0, orientation: self.imageOrientation).draw(in: blanceRect)
        return UIGraphicsGetImageFromCurrentImageContext()
    }

}

這是根據給定大小從中心裁剪圖像的 Swift 5 版本。

extension UIImage {

     func imageByCroppingImage(size : CGSize) -> UIImage{
        let refWidth : CGFloat = CGFloat(self.cgImage!.width)
        let refHeight : CGFloat = CGFloat(self.cgImage!.height)
        let x = (refWidth - size.width) / 2
        let y = (refHeight - size.height) / 2
        let cropRect = CGRect(x: x, y: y, width: size.width, height: size.height)
        let imageRef = self.cgImage!.cropping(to: cropRect)
        let cropped : UIImage = UIImage(cgImage: imageRef!, scale: 0, orientation: self.imageOrientation)
        return cropped
    }
    }

我能夠用這樣的東西來完成它:

   UIImage *thisImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
                double x = (thisImage.size.width )/2.0;
                double y = (thisImage.size.height)/2.0;
                mediaImage = [self imageByCropping:thisImage toRect:CGRectMake(x, y, 60, 60)];
                [thisImage release];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM