根据UIImageView UIViewContentMode中的可见区域裁剪UIImage

时间:2014-01-26 06:53:30

标签: ios objective-c uiview uiimageview uiimage

我在UIImage内设置UIImageViewUIImageView可以将其内容模式设置为可用的内容模式之一:

typedef NS_ENUM(NSInteger, UIViewContentMode) {
    UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,
};

我想裁剪图片,使比例与内容模式匹配。
这是如何实现的?

1 个答案:

答案 0 :(得分:1)

我不这样你可以使用内容模式来实现这一点。请尝试使用以下核心图形代码:

- (UIImage *)cropVisiblePortionOfImageView:(UIImageView *)imageView {

  CGFloat zoomScaleX=imageView.frame.size.width/initialWidth;
  CGFloat zoomScaleY=imageView.frame.size.height/initialHeight;
  CGSize zoomedSize=CGSizeMake(initialWidth*zoomScaleX,initialHeight*zoomScaleY);

  UIGraphicsBeginImageContext(zoomedSize);
  [imageView.image drawInRect:CGRectMake(0, 0, zoomedSize.width, zoomedSize.height)];
  UIImage *zoomedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  UIGraphicsBeginImageContext(CGSizeMake(initialWidth, initialHeight));
  [zoomedImage drawAtPoint:CGPointMake(imageView.frame.origin.x, imageView.frame.origin.y)];
  UIImage *cropedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return cropedImage;
}