在保留 alpha 的同时从阴影视图创建 UIImage?

Create UIImage from shadowed view while retaining alpha?(在保留 alpha 的同时从阴影视图创建 UIImage?)

本文介绍了在保留 alpha 的同时从阴影视图创建 UIImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不寻常的问题.在我的应用程序中,我使用基本的 Quartz2d 图层阴影来阴影 UIImageView.这是我的代码:

I have a somewhat unusual problem. In my app, I am shadowing a UIImageView using basic Quartz2d layer shadowing. Here's my code:

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

这会在图像视图后面产生很好的模糊效果.但是,我正在使用此视图制作一些动画,并且在过渡期间不断重新计算阴影会导致过渡非常不稳定.我想做的是从图像视图中创建一个 UIImage 或 .png 文件模糊和它的 alpha 完整.这是我已经尝试过的:

This produces a nice blur behind the image view. However, I am doing some animation with this view, and the constant recalculation of the shadowing during the transitions causes a very choppy transition. What I'd like to be able to do is create a UIImage or .png file out of the image view with the blur and its alpha intact. Here's what I've already tried:

UIGraphicsBeginImageContext(CGSizeMake(320, 396)); 
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

由于我有一个生长在"图像视图之外的阴影,我不能只在 UIGraphicsBeginImageContext 函数中传递他的大小.我设置了正确的大小,但生成的图像并没有保存我的 alpha,而是在阴影后面放置了一个白色背景,这对我不起作用,因为我的真实背景是木质纹理.此外,视图不在生成的文件中居中.

Since I have a shadow which "grows outside" of the image view, I can't just pass his size in the UIGraphicsBeginImageContext function. I set the correct size, but the resulting image doesn't save my alpha, instead it places a white background behind the shadow, which won't work for me because my real background is a wood texture. Also, the view isn't centered in the resulting file.

我很擅长 UIKit,但我是一个真正的 Quartz 2d 图形的菜鸟,所以如果有一个明显的答案,无论如何都发送它.:)

I'm pretty good with UIKit, but I'm a real noobie with Quartz 2d graphics, so if there's an obvious answer to this, send it anyway. :)

推荐答案

尝试将 UIImageViewbackgroundColor 设置为 [UIColor clearColor]- 这可能会使您当前的解决方案发挥作用.

Try setting your UIImageView's backgroundColor to [UIColor clearColor] - this may enable your current solution to work.

imageView.backgroundColor = [UIColor clearColor];
UIGraphicsBeginImageContext(CGSizeMake(320, 396)); 
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

来源:转换在 CoreGraphics iphone 中将 CGLayer 转换为 *transparent* UIImage 和 PNG 文件

这篇关于在保留 alpha 的同时从阴影视图创建 UIImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在保留 alpha 的同时从阴影视图创建 UIImage?

基础教程推荐