ios 如何设置 UIImage 的不透明度/alpha?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5084845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the opacity/alpha of a UIImage?
提问by Marty
I know you can do this with a UIImageView, but can it be done to a UIImage? I want to have the animation images array property of a UIImageView to be an array of the same image but with different opacities. Thoughts?
我知道你可以用 UIImageView 做到这一点,但它可以对 UIImage 做到吗?我想让 UIImageView 的动画图像数组属性成为相同图像但具有不同不透明度的数组。想法?
回答by Nick H247
I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:
我只需要这样做,但认为史蒂文的解决方案会很慢。这应该有希望使用图形硬件。在 UIImage 上创建一个类别:
- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextSetAlpha(ctx, alpha);
CGContextDrawImage(ctx, area, self.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
回答by Mats Stijlaart
Set the opacity of its view it is showed in.
设置其显示的视图的不透明度。
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]];
imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0
Use this in an animation. You can change the alpha in an animation for an duration.
在动画中使用它。您可以在一段时间内更改动画中的 Alpha。
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
//Set alpha
[UIView commitAnimations];
回答by Devin B
Based on Alexey Ishkov's answer, but in Swift
基于 Alexey Ishkov 的回答,但在 Swift 中
I used an extension of the UIImage class.
我使用了 UIImage 类的扩展。
Swift 2:
斯威夫特 2:
UIImage Extension:
UIImage 扩展:
extension UIImage {
func imageWithAlpha(alpha: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
drawAtPoint(CGPointZero, blendMode: .Normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
To use:
使用:
let image = UIImage(named: "my_image")
let transparentImage = image.imageWithAlpha(0.5)
Swift 3/4/5:
斯威夫特 3/4/5:
Note that this implementation returns an optional UIImage. This is because in Swift 3 UIGraphicsGetImageFromCurrentImageContext
now returns an optional. This value could be nil if the context is nil or what not created with UIGraphicsBeginImageContext
.
请注意,此实现返回一个可选的 UIImage。这是因为在 Swift 3UIGraphicsGetImageFromCurrentImageContext
现在返回一个可选的。如果上下文为零或不是用UIGraphicsBeginImageContext
.
UIImage Extension:
UIImage 扩展:
extension UIImage {
func image(alpha: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: .zero, blendMode: .normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
To use:
使用:
let image = UIImage(named: "my_image")
let transparentImage = image?.image(alpha: 0.5)
回答by Alexey Ishkov
there is much easier solution:
有更简单的解决方案:
- (UIImage *)tranlucentWithAlpha:(CGFloat)alpha
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
[self drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:alpha];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
回答by Steven Veltema
I realize this is quite late, but I needed something like this so I whipped up a quick and dirty method to do this.
我意识到这已经很晚了,但我需要这样的东西,所以我想出了一种快速而肮脏的方法来做到这一点。
+ (UIImage *) image:(UIImage *)image withAlpha:(CGFloat)alpha{
// Create a pixel buffer in an easy to use format
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
UInt8 * m_PixelBuf = malloc(sizeof(UInt8) * height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(m_PixelBuf, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
//alter the alpha
int length = height * width * 4;
for (int i=0; i<length; i+=4)
{
m_PixelBuf[i+3] = 255*alpha;
}
//create a new image
CGContextRef ctx = CGBitmapContextCreate(m_PixelBuf, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGImageRef newImgRef = CGBitmapContextCreateImage(ctx);
CGColorSpaceRelease(colorSpace);
CGContextRelease(ctx);
free(m_PixelBuf);
UIImage *finalImage = [UIImage imageWithCGImage:newImgRef];
CGImageRelease(newImgRef);
return finalImage;
}
回答by Nick Kovalsky
Hey hey thanks from Xamarin user! :) Here it goes translated to c#
嘿嘿,感谢 Xamarin 用户!:) 这里它被翻译成 c#
//***************************************************************************
public static class ImageExtensions
//***************************************************************************
{
//-------------------------------------------------------------
public static UIImage WithAlpha(this UIImage image, float alpha)
//-------------------------------------------------------------
{
UIGraphics.BeginImageContextWithOptions(image.Size,false,image.CurrentScale);
image.Draw(CGPoint.Empty, CGBlendMode.Normal, alpha);
var newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage;
}
}
Usage example:
用法示例:
var MySupaImage = UIImage.FromBundle("opaquestuff.png").WithAlpha(0.15f);
回答by pinch
same result as others, different style:
与其他人相同的结果,不同的风格:
extension UIImage {
func withAlpha(_ alpha: CGFloat) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
draw(at: .zero, blendMode: .normal, alpha: alpha)
}
}
}
回答by russes
If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:
如果您正在试验 Metal 渲染并在第一个回复中提取 imageByApplyingAlpha 生成的 CGImage,则最终可能会得到比预期更大的 Metal 渲染。在使用 Metal 进行试验时,您可能希望更改 imageByApplyingAlpha 中的一行代码:
UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
// UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);
If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.
如果您使用的是比例因子为 3.0 的设备,例如 iPhone 11 Pro Max,则上面显示的 0.0 比例因子将为您提供比预期大三倍的 CGImage。将比例因子更改为 1.0 应避免任何缩放。
Hopefully, this reply will save beginners a lot of aggravation.
希望这个回复可以为初学者省去很多麻烦。