在iPhone应用程序中将UIImage切成三角形

时间:2011-03-21 14:17:44

标签: iphone uiimage geometry slice image-clipping

我正在使用iPhone应用程序,我用相机拍照。此后,应该可以将图像切割成各种形状 - 最重要的三角形。任何人都可以给我一个正确的方向或例子等。我已经可以切成正方形而不是三角形。

(更新)为了创建平方切片,我使用了以下代码片段

CGRect ClippedRect= CGRectMake(0, 150, 320.0, 230.0);//example numbers
CGImageRef imageRef = CGImageCreateWithImageInRect([OriginalUIImage CGImage], ClippedRect);
UIImage *resultUIImage=[[UIImage alloc]initWithCGImage:imageRef];

感谢所有帮助

此致

解决:

我选择了掩盖uiimage的方法。所以策略是1.从相机拍摄照片和缩放。 2.让用户在uiimageview中绘制一个图形并用黑色填充它并从中创建一个UIImage。 3.使用用户生成的图像屏蔽来自摄像机的图像。 为了屏蔽图像,我使用http://www.developers-life.com/resize-and-mask-an-image.html

中的以下方法
- (UIImage*) maskImage:(UIImage *)image  {

 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

 UIImage *maskImage = [UIImage imageNamed:@"mask.png"];
 CGImageRef maskImageRef = [maskImage CGImage];

 // create a bitmap graphics context the size of the image
 CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);


 if (mainViewContentContext==NULL)
      return NULL;

 CGFloat ratio = 0;

 ratio = maskImage.size.width/ image.size.width;

 if(ratio * image.size.height < maskImage.size.height) {
      ratio = maskImage.size.height/ image.size.height;
 } 

 CGRect rect1  = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
 CGRect rect2  = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};


 CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
 CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);


 // Create CGImageRef of the main view bitmap content, and then
 // release that bitmap context
 CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
 CGContextRelease(mainViewContentContext);

 UIImage *theImage = [UIImage imageWithCGImage:newImage];

 CGImageRelease(newImage);

 // return the image
 return theImage;

}

感谢您的所有帮助

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:
http://iosdevelopertips.com/cocoa/how-to-mask-an-image.html
如果我得到正确的解释,只需将黑色图像作为蒙版并将其应用于图像。

答案 1 :(得分:0)

你应该可以使用这种方法:使用UIGraphicsBeginImageContextWithOptions创建一个新图像(你也可以使用CoreGraphics等效但更多工作),然后创建一个你想要的形状的bezier路径,调用{ {3}}然后在该上下文中绘制图像。然后,您可以使用[yourBezierPath addClip]获取生成的图像。务必在事后致电UIGraphicsEndImageContext()。有关使用UIGraphicsBeginImageContextWithOptions创建图片的信息,请参见UIGraphicsGetImageFromCurrentImageContext