iPhone中的剪切技巧:
1.获取图形上下文
2.构造剪切的路径(形状)
3.构建剪切区域
4.贴上你的画
- // 1
- CGContextRef context = UIGraphicsGetCurrentContext();
- // 2
- CGRect bounds = CGRectMake(0.0f, 0.0f, SIDELENGTH, SIDELENGTH);
- CGMutablePathRef path = CGPathCreateMutable();
- CGPathAddEllipseInRect(path, NULL, bounds);
- // 3
- CGContextAddPath(context, path);
- CGContextClip(context);
- // 4
- [LOGO drawInRect:bounds];
-(UIImage*)getClipImageRect:(CGRect)cropRect
{
CGImageRef imageRef =CGImageCreateWithImageInRect([self.photoCGImage], cropRect);
UIImage *result = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return result;
}
// Create appropriately modified image.
UIImage *image = nil;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
UIGraphicsBeginImageContextWithOptions(destRect.size, NO, 0.0); // 0.0 for scale means "correct scale for device's main screen".
CGImageRef sourceImg = CGImageCreateWithImageInRect([self CGImage], sourceRect); // cropping happens here.
image = [UIImage imageWithCGImage:sourceImg scale:0.0 orientation:self.imageOrientation]; // create cropped UIImage.
[image drawInRect:destRect]; // the actual scaling happens here, and orientation is taken care of automatically.
CGImageRelease(sourceImg);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
#endif
if (!image) {
// Try older method.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, fitSize.width, fitSize.height, 8, (fitSize.width * 4),
colorSpace, kCGImageAlphaPremultipliedLast);
CGImageRef sourceImg = CGImageCreateWithImageInRect([self CGImage], sourceRect);
CGContextDrawImage(context, destRect, sourceImg);
CGImageRelease(sourceImg);
CGImageRef finalImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
image = [UIImage imageWithCGImage:finalImage];
CGImageRelease(finalImage);
}