简体   繁体   English

比例和裁剪图像ios

[英]scale and crop image ios

I'm working in a function for scaling and crop image (similar to camara app) for iOS, the code below works fine, just that the resulting image came up side down, and I would like to understand why. 我正在为iOS进行缩放和裁剪图像(类似于camara应用程序)的功能,下面的代码工作正常,只是结果图像出现了,我想了解原因。

Thanks 谢谢

- (UIImage*)imageByCropping:(UIImageView *)imageViewToCrop toRect:(CGRect)rect
{
    //create a context to do our clipping in
    CGRect newRect = CGRectApplyAffineTransform(rect, imageViewToCrop.transform);
    UIImage *imageToCrop = imageViewToCrop.image;
    UIGraphicsBeginImageContext(newRect.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);


    //draw the image to our clipped context using our offset rect
    CGContextDrawImage(currentContext, newRect, imageToCrop.CGImage);

    //pull the image from our cropped context
    UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    return cropped;

} 

I've also came across this issue without explanation. 我也没有解释就遇到过这个问题。 But have found a workaround that solves that problem. 但是找到了解决这个问题的解决方法。 Just put the following two lines in your code and try it again. 只需在代码中添加以下两行并再次尝试。 It works for me. 这个对我有用。

CGContextTranslateCTM(context, 0.0, newRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);//flip context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM