来自UIImage的子图像

时间:2013-11-06 18:02:46

标签: ios uiimage draw

我已将PNG加载到UIImage中。我想基于路径获得图像的一部分(即它可能不是矩形)。比方说,它可能是弧形等形状。就像绘图路径一样。

最简单的方法是什么?

感谢。

2 个答案:

答案 0 :(得分:2)

我没有运行它,所以它可能不完美,但这应该给你一个想法。

UIImage *imageToClip = //get your image somehow
CGPathRef yourPath = //get your path somehow
CGImageRef imageRef = [imageToClip CGImage];

size_t width = CGImageGetWidth(imageRef);  
size_t height = CGImageGetHeight(imageRef);
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, CGImageGetColorSpace(imageRef), kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextAddPath(context, yourPath);
CGContextClip(context);

CGImageRef clippedImageRef = CGBitmapContextCreateImage(context);  
UIImage *clippedImage = [UIImage imageWithCGImage:clippedImageRef];//your final, masked image

CGImageRelease(clippedImageRef);
CGContextRelease(context);

答案 1 :(得分:1)

使用follow方法向UIImage添加类别的最简单方法:

-(UIImage *)scaleToRect:(CGRect)rect{
// Create a bitmap graphics context
// This will also set it as the current context
UIGraphicsBeginImageContext(size);

// Draw the scaled image in the current context
[self drawInRect:rect];

// Create a new image from current context
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

// Pop the current context from the stack
UIGraphicsEndImageContext();

// Return our new scaled image
return scaledImage;

}