我有一个相机应用程序将照片加载到带有遮罩的设备中。一切都好。当我尝试使用renderInContext将视图保存到图像时,我只看到没有任何蒙版的图像。
UIGraphicsBeginImageContext(contentView.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[contentView.layer renderInContext:context];
UIImage *outImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(outImage, self, @selector(image: didFinishSavingWithError: contextInfo:), context);
我从Apple那里读过一些文章,说renderInContext不支持掩码和组合。我在互联网上进行了一些搜索,以获取UIView首先需要绘制的信息作为上下文,然后使用renderInContext来保存图像。
现在我的问题是做什么工作的方法?那么drawRect,drawInRect,drawLayer,drawInContent或其他方法呢。任何人都可以给我一个提示。非常感谢。
答案 0 :(得分:0)
我有一个UIBezierPath,我想对它应用渐变并应用于现有图像,看看以下代码是否有帮助
CGRect r = CGRectMake(0, 0, HEART_SIZE, HEART_SIZE);
UIBezierPath *heart = [Bezier heartShape:r]; //this is only in my case
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
UIColor *darkPink = [UIColor colorWithHue:0.915 saturation:1.000 brightness:0.941 alpha:1.000];
UIColor *lightPink = [UIColor colorWithHue:0.917 saturation:0.647 brightness:1.000 alpha:1.000];
NSArray *gradientColors = [NSArray arrayWithObjects:
(id)darkPink.CGColor,
(id)lightPink.CGColor,
(id)darkPink.CGColor, nil];
CGFloat gradientLocations[] = {0, 0.5, 1};
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations);
CGColorSpaceRelease(colorSpace);
UIGraphicsBeginImageContext(r.size);
heart.lineCapStyle = kCGLineCapRound;
heart.lineWidth = 10.0f;
[[UIColor blackColor] setStroke];
[[UIColor redColor] setFill];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
[heart stroke]; //removed the black stroke around
[heart fill];
CGContextAddPath(context, heart.CGPath);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, CGPointMake(10, 10), CGPointMake(210, 210), kCGGradientDrawsAfterEndLocation); //check that gradient is drawn in the right place
CGGradientRelease(gradient);
UIImage *theRightImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();