充实自己的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)];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值