从阴影视图创buildUIImage,同时保留alpha?
我有一个不寻常的问题。 在我的应用程序中,我使用基本的Quartz2d图层阴影来遮挡UIImageView
。 这是我的代码:
imageView.layer.shadowOpacity = 1.0; // Pretty self explanatory imageView.layer.shadowRadius = 8.0; // My softness imageView.layer.shadowColor = [UIColor blackColor].CGColor; // Color of the shadow imageView.layer.shadowOffset = CGSizeMake(0.0, 0.0); // Offset of the shadow
这在图像视图背后产生了很好的模糊效果。 不过,我正在用这种观点来做一些animation,在转换过程中对阴影的不断重新计算会导致非常波动的过渡。 我希望能够做的是创build一个UIImage或.png文件的图像视图与模糊和其alpha保持不变 。 这是我已经尝试过的:
UIGraphicsBeginImageContext(CGSizeMake(320, 396)); [imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
由于我有一个“图像视图外部”增长的阴影,我不能只在UIGraphicsBeginImageContext
函数中传递它的大小。 我设置了正确的大小,但是由此产生的图像并不能保存我的alpha,而是在阴影后面放置了一个白色背景,这对我来说不起作用,因为我的真实背景是木质纹理。 另外,该视图不在生成的文件中。
我对UIKit
相当不错,但是我是一个真正的使用Quartz
2D绘图的noobie,所以如果有一个明显的答案,无论如何发送它。 🙂
尝试设置您的UIImageView
的backgroundColor
到[UIColor clearColor]
– 这可能使您当前的解决scheme工作。
imageView.backgroundColor = [UIColor clearColor]; UIGraphicsBeginImageContext(CGSizeMake(320, 396)); [imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
源代码: 在CoreGraphics iphone中将CGLayer转换为* transparent * UIImage和PNG文件
我也有过这个问题。 我的解决scheme是不做一个图像,而是将阴影path设置为您正在animation的视图的轮廓。
[imageView setContentMode:UIViewContentModeScaleAspectFit]; imageView.layer.masksToBounds = NO; imageView.layer.shadowOffset = CGSizeMake(5, 5); imageView.layer.shadowRadius = 200; imageView.layer.shadowOpacity = 0.5; CGRect rect = [self rectFromImageView:imageView]; imageView.layer.shadowPath = [UIBezierPath bezierPathWithRect:rect].CGPath;
其中使用以下function,假定图像设置为内容模式方面适合:
-(CGRect)rectFromImageView:(UIImageView *)iv { CGRect rect = (CGRect){{0,0},iv.frame.size}; if (iv.image.size.width/iv.frame.size.width > iv.image.size.height/iv.frame.size.height) { //rect.origin.x == 0 CGFloat sf = iv.frame.size.width/iv.image.size.width; rect.size.height = sf*iv.image.size.height; rect.origin.y = floor((iv.frame.size.height - rect.size.height)/2); } else { //rect.origin.y == 0; CGFloat sf = iv.frame.size.height/iv.image.size.height; rect.size.width = sf*iv.image.size.width; rect.origin.x = floor((iv.frame.size.width - rect.size.width)/2); } return rect; }
如果你的图像只是设置填充,那么只使用imageView.bounds
应该是足够的
添加阴影path来查看像这样
[view.layer setShadowPath:[[UIBezierPath bezierPathWithRect:view.bounds] CGPath]]; //add path view.layer.shadowColor = [[UIColor blackColor] CGColor]; view.layer.shadowOffset = CGSizeMake(x, y); view.layer.shadowRadius = rad; view.layer.shadowOpacity = 0.2f;