programing

UI 이미지 자르기

powerit 2023. 5. 18. 21:30
반응형

UI 이미지 자르기

할 수 있는 있습니다 - 의 크기를 할 수 있습니다 - 저는 이것을 사용하여 조코지중크크이수정기있미드습니. 다이사크이조를니합다정기중의여앙미지하용코드를이미가앙의는도있지를기하록를정조할▁a▁i▁that다▁this니조합▁to▁of▁so정▁i▁take▁use▁of를▁code크▁-▁res▁chunk▁i▁image기▁an▁center▁got이ve▁some'izes미▁a▁image▁scaled▁get▁the▁the.UIImage사진 앱의 앨범 보기에서 볼 수 있는 것과 유사한 작고 정사각형의 이미지 표현을 반환합니다. (사용할 수 있음을 알고 있습니다.)UIImageView그리고 같은 결과를 얻기 위해 자르기 모드를 조정하지만 이러한 이미지는 때때로 다음에 표시됩니다.UIWebViews).

저는 이 코드에서 충돌을 발견하기 시작했고 조금 당황스럽습니다.저는 두 가지 다른 이론을 가지고 있는데 둘 중 하나가 근거에 있는지 궁금합니다.

이론 1) 목표 크기의 오프스크린 이미지 컨텍스트에 그림을 그려서 자르기를 달성합니다.이미지의 중앙 부분을 원하기 때문에, 저는 다음과 같이 설정합니다.CGRect가 에게전논에게 전달되었습니다.drawInRect내 이미지 맥락의 한계보다 더 큰 것으로.저는 이것이 코셔이기를 바랐지만, 제가 만져서는 안 되는 다른 기억을 끌어내려고 하는 것일까요?

이론 2) 저는 이 모든 것을 백그라운드 스레드에서 수행하고 있습니다.UIKit에서 메인 스레드로 제한되는 부분이 있는 것으로 알고 있습니다.저는 오프스크린 뷰에 그림을 그리는 것이 이것들 중 하나가 아니길 바라고 있었습니다.내가 틀렸나요?

(오, 내가 그리워하는 것은NSImage's drawInRect:fromRect:operation:fraction:방법).

업데이트 2014-05-28: iOS 3 정도가 최신 유행일 때 이 글을 썼습니다. 지금쯤이면 이를 위한 더 나은 방법이 있을 것이라고 확신합니다. 아마도 내장되어 있을 것입니다.많은 사람들이 언급했듯이, 이 방법은 순환을 고려하지 않습니다; 추가적인 답변을 읽고 이 질문에 대한 대답을 모두에게 도움이 되도록 하기 위해 사랑을 퍼뜨립니다.

원래 응답:

동일한 질문에 대한 답변을 다른 곳에 복사/붙여넣습니다.

할 수 : 이를위한할해 간 단 클 한 수 사 있 기 있 이 능 습 다 니 는 용 위 얻 결 기 원 과 를 는 하 없 방 만 지 래 법 스 은 ▁there 다CGImageCreateWithImageInRect(CGImageRef, CGRect)당신을 도와줄 겁니다.

다음은 이 기능을 사용한 간단한 예입니다.

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
// or use the UIImage wherever you like
[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; 
CGImageRelease(imageRef);

동일한 스케일과 방향을 유지하면서 망막 영상을 자르기 위해서는 UII 영상 범주(iOS 4.0 이상)에서 다음 방법을 사용합니다.

- (UIImage *)crop:(CGRect)rect {
    if (self.scale > 1.0f) {
        rect = CGRectMake(rect.origin.x * self.scale,
                          rect.origin.y * self.scale,
                          rect.size.width * self.scale,
                          rect.size.height * self.scale);
    }

    CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

UI 이미지 카테고리를 만들어 필요한 곳 어디서나 사용할 수 있습니다.HitScan 응답 및 아래 설명을 기반으로 합니다.

@implementation UIImage (Crop)

- (UIImage *)crop:(CGRect)rect {

    rect = CGRectMake(rect.origin.x*self.scale, 
                      rect.origin.y*self.scale, 
                      rect.size.width*self.scale, 
                      rect.size.height*self.scale);       

    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef 
                                          scale:self.scale 
                                    orientation:self.imageOrientation]; 
    CGImageRelease(imageRef);
    return result;
}

@end

다음과 같은 방법으로 사용할 수 있습니다.

UIImage *imageToCrop = <yourImageToCrop>;
CGRect cropRect = <areaYouWantToCrop>;   

//for example
//CGRectMake(0, 40, 320, 100);

UIImage *croppedImage = [imageToCrop crop:cropRect];

스위프트 3 버전

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


let imageTop:UIImage  = UIImage(named:"one.jpg")! // add validation

여기에 이미지 설명 입력

기능의 으로.CGRectMake->CGRect( 답변에 대한 답변은 다음과 같습니다.)@rob mayoff):

 func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
    return CGRect(x: x, y: y, width: width, height: height)
}

용도:

if var image:UIImage  = UIImage(named:"one.jpg"){
   let  croppedImage = cropImage(imageToCrop: image, toRect: CGRectMake(
        image.size.width/4,
        0,
        image.size.width/2,
        image.size.height)
    )
}

출력:

여기에 이미지 설명 입력

다음은 imageOrientation 속성을 준수하는 UIImage 자르기 구현입니다.모든 방향을 철저히 테스트했습니다.

inline double rad(double deg)
{
    return deg / 180.0 * M_PI;
}

UIImage* UIImageCrop(UIImage* img, CGRect rect)
{
    CGAffineTransform rectTransform;
    switch (img.imageOrientation)
    {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };
    rectTransform = CGAffineTransformScale(rectTransform, img.scale, img.scale);

    CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], CGRectApplyAffineTransform(rect, rectTransform));
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:img.scale orientation:img.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

주의: 이 모든 대답은 다음을 가정합니다.CGImage백업된 이미지 개체입니다.

image.CGImage 반 할 수 있습니다을인 0을할 수 .UIImage의 지원을 받습니다.CIImage만약 당신이 이 이미지를 사용하여 만든다면 그럴 것입니다.CIFilter.

이 경우 새 컨텍스트에서 이미지를 그려야 하고 해당 이미지를 반환해야 할 수도 있습니다(느림).

UIImage* crop(UIImage *image, rect) {
    UIGraphicsBeginImageContextWithOptions(rect.size, false, [image scale]);
    [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];
    cropped_image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return cropped_image;
}

여기에 나와 있는 답 중에 스케일 및 회전 문제를 100% 정확하게 처리하는 것은 없습니다.iOS 7/8의 최신 버전으로 지금까지 언급된 모든 내용을 종합한 것입니다.UI 이미지의 카테고리에 메소드로 포함되도록 되어 있습니다.

- (UIImage *)croppedImageInRect:(CGRect)rect
{
    double (^rad)(double) = ^(double deg) {
        return deg / 180.0 * M_PI;
    };

    CGAffineTransform rectTransform;
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -self.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -self.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -self.size.width, -self.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };
    rectTransform = CGAffineTransformScale(rectTransform, self.scale, self.scale);

    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], CGRectApplyAffineTransform(rect, rectTransform));
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    CGImageRelease(imageRef);

    return result;
}

의 빠른 버전awolf나에게 효과가 있었던 대답:

public extension UIImage {
    func croppedImage(inRect rect: CGRect) -> UIImage {
        let rad: (Double) -> CGFloat = { deg in
            return CGFloat(deg / 180.0 * .pi)
        }
        var rectTransform: CGAffineTransform
        switch imageOrientation {
        case .left:
            let rotation = CGAffineTransform(rotationAngle: rad(90))
            rectTransform = rotation.translatedBy(x: 0, y: -size.height)
        case .right:
            let rotation = CGAffineTransform(rotationAngle: rad(-90))
            rectTransform = rotation.translatedBy(x: -size.width, y: 0)
        case .down:
            let rotation = CGAffineTransform(rotationAngle: rad(-180))
            rectTransform = rotation.translatedBy(x: -size.width, y: -size.height)
        default:
            rectTransform = .identity
        }
        rectTransform = rectTransform.scaledBy(x: scale, y: scale)
        let transformedRect = rect.applying(rectTransform)
        let imageRef = cgImage!.cropping(to: transformedRect)!
        let result = UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
        return result
    }
}

swift3

extension UIImage {
    func crop(rect: CGRect) -> UIImage? {
        var scaledRect = rect
        scaledRect.origin.x *= scale
        scaledRect.origin.y *= scale
        scaledRect.size.width *= scale
        scaledRect.size.height *= scale
        guard let imageRef: CGImage = cgImage?.cropping(to: scaledRect) else {
            return nil
        }
        return UIImage(cgImage: imageRef, scale: scale, orientation: imageOrientation)
    }
}
CGSize size = [originalImage size];
int padding = 20;
int pictureSize = 300;
int startCroppingPosition = 100;
if (size.height > size.width) {
    pictureSize = size.width - (2.0 * padding);
    startCroppingPosition = (size.height - pictureSize) / 2.0; 
} else {
    pictureSize = size.height - (2.0 * padding);
    startCroppingPosition = (size.width - pictureSize) / 2.0;
}
// WTF: Don't forget that the CGImageCreateWithImageInRect believes that 
// the image is 180 rotated, so x and y are inverted, same for height and width.
CGRect cropRect = CGRectMake(startCroppingPosition, padding, pictureSize, pictureSize);
CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect);
UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:originalImage.imageOrientation];
[m_photoView setImage:newImage];
CGImageRelease(imageRef);

제가 본 대부분의 응답은 (x, y)에 대해 (0, 0)의 위치만 다루고 있습니다.네, 한 가지 경우지만 제 작물 작업이 중심이 되었으면 합니다.제가 알아내는데 시간이 좀 걸린 것은 WTF 코멘트 뒤에 이어지는 대사입니다.

세로 방향으로 캡처한 이미지의 경우를 예로 들어보겠습니다.

  1. 원본 이미지 높이가 너비보다 높습니다(Woo, 아직까지는 놀라운 점이 없습니다!)
  2. CGIimageCreateWithImageInRect 메서드가 자체 세계에서 상상하는 이미지는 실제로는 초상화가 아니라 풍경화입니다(또한 이미지에서 방향 인수를 사용하지 않는 경우).CGImage 생성기를 사용하면 180회전으로 표시됩니다.
  3. (0, 0) 위치가 이미지의 오른쪽 상단 모서리인 풍경이라고 상상해야 합니다.

그것이 말이 되기를 바랍니다!그렇지 않은 경우 다른 값을 사용해 보십시오. cropRect에 맞는 x, y, 너비 및 높이를 선택할 때 논리가 반전됩니다.

신속한 확장

extension UIImage {
    func crop(var rect: CGRect) -> UIImage {
        rect.origin.x*=self.scale
        rect.origin.y*=self.scale
        rect.size.width*=self.scale
        rect.size.height*=self.scale

        let imageRef = CGImageCreateWithImageInRect(self.CGImage, rect)
        let image = UIImage(CGImage: imageRef, scale: self.scale, orientation: self.imageOrientation)!
        return image
    }
}

정밀도, 픽셀 스케일링 측면에서 Swift에서 UI 이미지를 자르기 위한 최상의 솔루션...:

private func squareCropImageToSideLength(let sourceImage: UIImage,
    let sideLength: CGFloat) -> UIImage {
        // input size comes from image
        let inputSize: CGSize = sourceImage.size

        // round up side length to avoid fractional output size
        let sideLength: CGFloat = ceil(sideLength)

        // output size has sideLength for both dimensions
        let outputSize: CGSize = CGSizeMake(sideLength, sideLength)

        // calculate scale so that smaller dimension fits sideLength
        let scale: CGFloat = max(sideLength / inputSize.width,
            sideLength / inputSize.height)

        // scaling the image with this scale results in this output size
        let scaledInputSize: CGSize = CGSizeMake(inputSize.width * scale,
            inputSize.height * scale)

        // determine point in center of "canvas"
        let center: CGPoint = CGPointMake(outputSize.width/2.0,
            outputSize.height/2.0)

        // calculate drawing rect relative to output Size
        let outputRect: CGRect = CGRectMake(center.x - scaledInputSize.width/2.0,
            center.y - scaledInputSize.height/2.0,
            scaledInputSize.width,
            scaledInputSize.height)

        // begin a new bitmap context, scale 0 takes display scale
        UIGraphicsBeginImageContextWithOptions(outputSize, true, 0)

        // optional: set the interpolation quality.
        // For this you need to grab the underlying CGContext
        let ctx: CGContextRef = UIGraphicsGetCurrentContext()
        CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh)

        // draw the source image into the calculated rect
        sourceImage.drawInRect(outputRect)

        // create new image from bitmap context
        let outImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()

        // clean up
        UIGraphicsEndImageContext()

        // pass back new image
        return outImage
}

이 함수를 호출하는 데 사용되는 지침:

let image: UIImage = UIImage(named: "Image.jpg")!
let squareImage: UIImage = self.squareCropImageToSideLength(image, sideLength: 320)
self.myUIImageView.image = squareImage

참고: 목표-C로 작성된 초기 소스 코드 영감은 "코코아네틱스" 블로그에서 발견되었습니다.

아래 코드 조각이 도움이 될 수 있습니다.

import UIKit

extension UIImage {
    func cropImage(toRect rect: CGRect) -> UIImage? {
        if let imageRef = self.cgImage?.cropping(to: rect) {
            return UIImage(cgImage: imageRef)
        }
        return nil
    }
}

약간 이상하게 보이지만 작동이 잘 되고 이미지 방향을 고려합니다.

var image:UIImage = ...

let img = CIImage(image: image)!.imageByCroppingToRect(rect)
image = UIImage(CIImage: img, scale: 1, orientation: image.imageOrientation)
- (UIImage *)getSubImage:(CGRect) rect{
    CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    CGRect smallBounds = CGRectMake(rect.origin.x, rect.origin.y, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));

    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImg = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();

    return smallImg;
}
 (UIImage *)squareImageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    double ratio;
    double delta;
    CGPoint offset;

    //make a new square size, that is the resized imaged width
    CGSize sz = CGSizeMake(newSize.width, newSize.width);

    //figure out if the picture is landscape or portrait, then
    //calculate scale factor and offset
    if (image.size.width > image.size.height) {
        ratio = newSize.width / image.size.width;
        delta = (ratio*image.size.width - ratio*image.size.height);
        offset = CGPointMake(delta/2, 0);
    } else {
        ratio = newSize.width / image.size.height;
        delta = (ratio*image.size.height - ratio*image.size.width);
        offset = CGPointMake(0, delta/2);
    }

    //make the final clipping rect based on the calculated values
    CGRect clipRect = CGRectMake(-offset.x, -offset.y,
                                 (ratio * image.size.width) + delta,
                                 (ratio * image.size.height) + delta);


    //start a new context, with scale factor 0.0 so retina displays get
    //high quality image
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);
    } else {
        UIGraphicsBeginImageContext(sz);
    }
    UIRectClip(clipRect);
    [image drawInRect:clipRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

iOS 9.2SDK에서 아래 방법을 사용하여 프레임을 UIView에서 UIImage로 변환합니다.

-(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect
{
  CGSize cropSize = rect.size;
  CGFloat widthScale = image.size.width/self.imageViewOriginal.bounds.size.width;
  CGFloat heightScale = image.size.height/self.imageViewOriginal.bounds.size.height;
  cropSize = CGSizeMake(rect.size.width*widthScale, 
              rect.size.height*heightScale);
  CGPoint pointCrop = CGPointMake(rect.origin.x*widthScale,
             rect.origin.y*heightScale);
  rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, cropSize.height);
  CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);
  UIImage *croppedImage = [UIImage imageWithCGImage:subImage];
  CGImageRelease(subImage);

  return croppedImage;
}

Swift 2.0 업데이트(CIImage호환성)

Maxim's Answer에서 확장하지만 이미지가 다음과 같은 경우 작동합니다.CIImage기반도 있습니다.

public extension UIImage {
    func imageByCroppingToRect(rect: CGRect) -> UIImage? {
        if let image = CGImageCreateWithImageInRect(self.CGImage, rect) {
            return UIImage(CGImage: image)
        } else if let image = (self.CIImage)?.imageByCroppingToRect(rect) {
            return UIImage(CIImage: image)
        }
       return nil
   }
}

Noods 답변을 기반으로 업데이트된 Swift 3 버전입니다.

func cropping(to rect: CGRect) -> UIImage? {

    if let cgCrop = cgImage?.cropping(to: rect) {
        return UIImage(cgImage: cgCrop)
    }
    else if let ciCrop = ciImage?.cropping(to: rect) {
        return UIImage(ciImage: ciCrop)
    }

    return nil
}

@Arne의 응답을 따릅니다.그냥 카테고리 기능으로 수정합니다.UI 이미지 범주에 넣습니다.

-(UIImage*)cropImage:(CGRect)rect{

    UIGraphicsBeginImageContextWithOptions(rect.size, false, [self scale]);
    [self drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];
    UIImage* cropped_image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return cropped_image;
}

스위프트 5:

extension UIImage {
    func cropped(rect: CGRect) -> UIImage? {
        guard let cgImage = cgImage else { return nil }

        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        let context = UIGraphicsGetCurrentContext()

        context?.translateBy(x: 0.0, y: self.size.height)
        context?.scaleBy(x: 1.0, y: -1.0)
        context?.draw(cgImage, in: CGRect(x: rect.minX, y: rect.minY, width: self.size.width, height: self.size.height), byTiling: false)


        let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return croppedImage
    }
}

다른 솔루션은 여러 번 그리거나(필요 이상의 힘을 사용함) 방향 설정에 문제가 있어서 만족하지 못했습니다.UIImage* 이미지에서 축소된 사각 자르기 이미지에 사용한 내용입니다.

CGFloat minimumSide = fminf(image.size.width, image.size.height);
CGFloat finalSquareSize = 600.;

//create new drawing context for right size
CGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);
CGFloat scalingRatio = 640.0/minimumSide;
UIGraphicsBeginImageContext(rect.size);

//draw
[image drawInRect:CGRectMake((minimumSide - photo.size.width)*scalingRatio/2., (minimumSide - photo.size.height)*scalingRatio/2., photo.size.width*scalingRatio, photo.size.height*scalingRatio)];

UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

저는 아래의 방법을 사용합니다.

  -(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect
  {
    CGSize cropSize = rect.size;
    CGFloat widthScale =  
    image.size.width/self.imageViewOriginal.bounds.size.width;
    CGFloat heightScale = 
    image.size.height/self.imageViewOriginal.bounds.size.height;
    cropSize = CGSizeMake(rect.size.width*widthScale,  
    rect.size.height*heightScale);
    CGPoint  pointCrop = CGPointMake(rect.origin.x*widthScale, 
    rect.origin.y*heightScale);
    rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, 
    cropSize.height);
    CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);
    UIImage *croppedImage = [UIImage imageWithCGImage:subImage];
    CGImageRelease(subImage);
    return croppedImage;

}

https://github.com/vvbogdan/BVCropPhoto 을 보세요.

(UIImage *)잘린 이미지 {CGFloat 척도 = 자체.sourceImage.size.width / self.scrollView.contentSize.폭;
UI 이미지 *최종 이미지 = 0;
CGRect 대상 프레임 = CGRectMake(self.scrollView.content)inset.left + self.scrollView.contentOffset.x) * 척도,(self.scrollView.content)inset.top + self.scrollView.contentOffset.y) * 척도,self.cropSize.너비 * 척도,self.cropSize.높이 * 척도);

CGImageRef contextImage = CGImageCreateWithImageInRect([[회전이 있는 self.sourceImage] CGImage], targetFrame);

if (contextImage!= NULL) {final Image = [UII Image With CGImage:context Image척도:self.sourceImage.척도방향:UI 이미지 방향 설정];

CGI 이미지 릴리스(컨텍스트 이미지);
}
최종 이미지를 반환합니다.}

(UIImage *)회전이 있는 이미지:(UIImage *)이미지 {

if(image.imageOrientation == UIImageOrientationUp) 이미지를 반환합니다.CGAfine Transform 변환 = CGAfine Transform Identity;
스위치(image.imageOrientation) {case UI이미지 방향 다운:
case UIImageOrientationDownMirrored:
transform = CGAfineTransformTransform(변환, image.size).폭, 이미지.크기.높이);
변환 = CGAfine Transform Rotate(변환, M_PI);
브레이크;
case UI이미지 방향 왼쪽:case UIImageOrientation LeftMirrored:
transform = CGAfineTransformTransform(변환, image.size).폭, 0);변환 = CGAfine Transform Rotate(변환, M_PI_2);
브레이크;
case UI이미지 방향 오른쪽:case UI이미지 방향오른쪽 미러링:
변환 = CGAfine Transform Translate(변환, 0, 이미지.크기.높이);
변환 = CGAfine Transform Rotate(변환, -M_PI_2);
브레이크;case UI이미지 방향 설정:
case UIImageOrientationUpMirrored:
브레이크;}
스위치(image.imageOrientation) {case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAfineTransformTransform(변환, image.size).폭, 0);변환 = CGAfine Transform Scale(변환, -1, 1);브레이크;
case UIImageOrientation LeftMirrored:
case UI이미지 방향오른쪽 미러링:
변환 = CGAfine Transform Translate(변환, 이미지.size.높이, 0);변환 = CGAfine Transform Scale(변환, -1, 1);브레이크;case UI이미지 방향 설정:
case UI이미지 방향 다운:
case UI이미지 방향 왼쪽:case UI이미지 방향 오른쪽:브레이크;}
이제 변환을 적용하여 기본 CGI 이미지를 새로운 컨텍스트로 끌어옵니다.위에서 계산한
CGContextReftx = CGBitmapContextCreate(NULL, image.size).너비, 이미지.크기.높이,CGIageGetBitsPerComponent(이미지).CGImage), 0,CGIageGetColorSpace(이미지).CGImage),CGIageGetBitmapInfo(이미지).CGI 이미지);CGContextContextCTM(ctx, 변환);
스위치(image.imageOrientation) {case UI이미지 방향 왼쪽:case UIImageOrientation LeftMirrored:
case UI이미지 방향 오른쪽:case UI이미지 방향오른쪽 미러링:
이런...
CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.height, image.size).너비), 이미지.CGImage);
브레이크;
기본값:CGContextDrawImage(ctx, CGRectMake(0, 0, image.size)입니다.너비, 이미지.크기.높이), 이미지.CGImage);
브레이크;}
이제 도면 컨텍스트에서 새 UI 이미지를 만듭니다.CGImageRefgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImageWithCGImage:cgimg];
CG 컨텍스트 릴리스(ctx);
CGI 이미지 릴리스(cgimg);
return img;
}

신속한 5.0 업데이트

public extension UIImage {
    func cropped(rect: CGRect) -> UIImage? {
        if let image = self.cgImage!.cropping(to: rect) {
            return UIImage(cgImage: image)
        } else if let image = (self.ciImage)?.cropped(to: rect) {
            return UIImage(ciImage: image)
        }
       return nil
   }
}

Swift 5의 경우 다음 솔루션을 사용했습니다(중앙에서 잘라낸 이미지가 필요했습니다).

public extension UIImage {
func cropped(rect: CGRect) -> UIImage? {
    if let image = self.cgImage?.cropping(to: rect) {
        return UIImage(cgImage: image, scale:self.scale, orientation:self.imageOrientation)
    }
    return nil
}

}

코드 어딘가에 UIImage와 같은 "이미지"가 있습니다.

    let baseSize = image.size
    let delta = abs(baseSize.height - baseSize.width)/2.0

    let croppedFrame = baseSize.height > baseSize.width ? CGRect(x: 0, y: delta, width: baseSize.width, height: baseSize.width) :
                                                          CGRect(x: delta, y: 0, width: baseSize.height, height: baseSize.height)
    
    guard let croppedImage = image.cropped(rect: croppedFrame) else {
        return
    }

언급URL : https://stackoverflow.com/questions/158914/cropping-an-uiimage

반응형