Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the opacity/alpha of a UIImage?

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?

like image 760
Marty Avatar asked Feb 22 '11 22:02

Marty


People also ask

How do I change the opacity of an image in Swift?

Any SwiftUI view can be partially or wholly transparent using the opacity() modifier. This accepts a value between 0 (completely invisible) and 1 (fully opaque), just like the alpha property of UIView in UIKit.

Is opacity and alpha same?

Alpha affects everything drawn on the view. The background color's alpha affects the background color's transparency and anything else drawn on the view. i.e it brings about a frosty effect to whole view. Opacity means don't draw anything underneath, even if you are transparent, it just effects the current view.

What is the difference between UIImage and UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

What is Alpha in Swift?

alpha = 0.5 is that the label will have an opacity of 50% as well, so I figured out that it maybe would be possible to have a UIView with white background color and opacity (white_view), and then have another UIView with the label (label_view).


2 Answers

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 *)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; } 
like image 92
Nick Hingston Avatar answered Sep 29 '22 19:09

Nick Hingston


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.

[UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:1.0]; //Set alpha [UIView commitAnimations]; 
like image 32
Mats Stijlaart Avatar answered Sep 29 '22 20:09

Mats Stijlaart