充实自己的ios库 – UIImage相关

来源:互联网 发布:54捕鱼源码 编辑:程序博客网 时间:2024/04/28 19:07

充实自己的ios库 – UIImage相关

这两天研究OpenFlow,认为几个UIImage相关的函数很有意义,以后可能会用到,故拿出来分享,可以用来建立自己的“Category”库

1 将图片scale为新的size

- (UIImage *)rescaleImageToSize:(CGSize)size {        CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height);        UIGraphicsBeginImageContext(rect.size);        [self drawInRect:rect];  // scales image to rect        UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();        UIGraphicsEndImageContext();        return resImage;}

2 截取图像中的指定区域,返回结果图像

- (UIImage *)cropImageToRect:(CGRect)cropRect {        // Begin the drawing (again)        UIGraphicsBeginImageContext(cropRect.size);        CGContextRef ctx = UIGraphicsGetCurrentContext();        // Tanslate and scale upside-down to compensate for        //Quartz's inverted coordinate system        CGContextTranslateCTM(ctx, 0.0, cropRect.size.height);        CGContextScaleCTM(ctx, 1.0, -1.0);        // Draw view into context        CGRect drawRect = CGRectMake(               -cropRect.origin.x,               cropRect.origin.y-(self.size.height-cropRect.size.height),               self.size.width, self.size.height);        CGContextDrawImage(ctx, drawRect, self.CGImage);        // Create the new UIImage from the context        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();        // End the drawing        UIGraphicsEndImageContext();        return newImage;}

3 通过一个选定区域大小,计算和图像“等比”的相应区域大小

- (CGSize)calculateNewSizeForCroppingBox:(CGSize)croppingBox {        // Make the shortest side be equivalent to the cropping box.        CGFloat newHeight, newWidth;        if (self.size.width < self.size.height) {                newWidth = croppingBox.width;                newHeight = (self.size.height / self.size.width)                                                * croppingBox.width;        } else {                newHeight = croppingBox.height;                newWidth = (self.size.width / self.size.height)                                              * croppingBox.height;        }        return CGSizeMake(newWidth, newHeight);}

4 通过一个选定区域,得到和这个选定区域相应等比大小的图像(与原图像的中心对齐)

- (UIImage *)cropCenterAndScaleImageToSize:(CGSize)cropSize {        UIImage *scaledImage = [self rescaleImageToSize:                [self calculateNewSizeForCroppingBox:cropSize]];        return [scaledImage                cropImageToRect:CGRectMake(                               (scaledImage.size.width-cropSize.width)/2,                               (scaledImage.size.height-cropSize.height)/2,                               cropSize.width, cropSize.height)];}
原创粉丝点击