Как обрезать UIImage в iPhone? - PullRequest
0 голосов
/ 31 августа 2011

В моем приложении я установил одно изображение в UIImageView, а размер UIImageView составляет 320 x 170. Но размер исходного изображения составляет 320 x 460. Как обрезать это изображение и отобразить в UIImageView.

Ответы [ 3 ]

10 голосов
/ 31 августа 2011

Вот хороший способ обрезать изображение в CGRect:

- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect

{

   //create a context to do our clipping in

   UIGraphicsBeginImageContext(rect.size);

   CGContextRef currentContext = UIGraphicsGetCurrentContext();

   //create a rect with the size we want to crop the image to
   //the X and Y here are zero so we start at the beginning of our
   //newly created context

   CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);

   CGContextClipToRect( currentContext, clippedRect);

   //create a rect equivalent to the full size of the image
   //offset the rect by the X and Y we want to start the crop
   //from in order to cut off anything before them

   CGRect drawRect = CGRectMake(rect.origin.x * -1,
                                rect.origin.y * -1,
                                imageToCrop.size.width,
                                imageToCrop.size.height);

   //draw the image to our clipped context using our offset rect

   CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);

   //pull the image from our cropped context

   UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

   //pop the context to get back to the default

   UIGraphicsEndImageContext();

   //Note: this is autoreleased

   return cropped;

}

Или другим способом:

- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
     

{
  CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
    

  UIImage *cropped = [UIImage imageWithCGImage:imageRef];

  CGImageRelease(imageRef);


      return cropped;
    

}

С http://www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/.

3 голосов
/ 31 августа 2011

Вы можете вызвать эту функцию для обрезки изображения -

- (UIImage *)resizeImage:(UIImage *)oldImage width:(float)imageWidth height:(float)imageHeight {
    UIImage *newImage = oldImage;

    CGSize itemSize = CGSizeMake(imageWidth, imageHeight);
    UIGraphicsBeginImageContext(itemSize);
    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
    [oldImage drawInRect:imageRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

эта функция возвращает UIImage.

0 голосов
/ 09 июня 2016

Может быть, кто-то интересуется версией Swift ответа, который дал @tirth.Он написан как расширение UIImage.В качестве примера я добавил другой метод для обрезки изображения до версии с квадратным центром.

    // MARK: - UIImage extension providing function to crop an image to a rect
    extension UIImage {
        /**
         Return a cropped image from an existing image

         - parameter toRect: a rectangular region for a new image

         - returns: new image instance
         */
        func croppedImage(toRect: CGRect) -> UIImage {
            // create new CGImage reference
            let imageRef = CGImageCreateWithImageInRect(self.CGImage, toRect)
            // create and return new UIImage
            return UIImage(CGImage: imageRef!)
        }

        /**
         Crop center rect from possibly rectangular image

         - returns: return self in case image is already square, new center rect otherwise
         */
        func cropCenterRect() -> UIImage {
            // image might already be square
            if self.size.height == self.size.width {
                return self
            }
            // portrait
            if self.size.height > self.size.width {
                // calculate offset at top and bottom
                let offset = (self.size.height - self.size.width) / 2.0
                // return cropped image
                return self.croppedImage(CGRect(x: 0.0, y: offset, width: self.size.width, height: self.size.width))
            } else {
                // landscape
                // calculate offset left and right
                let offset = (self.size.width - self.size.height) / 2.0
                // return cropped image
                return self.croppedImage(CGRect(x: offset, y: 0.0, width: self.size.height, height: self.size.height))
            }
        }
    }
...