How to set the alpha of an UIImage in SWIFT programmatically?
Luckily I was able to help myself and would like to share with you my solution:
Swift 3
// UIImage+Alpha.swift
extension UIImage {
func alpha(_ value:CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
The above new Swift extension I added to my project and then I changed the UIButton example as follows, to have an alpha transparent background image with a transparency of 50%.
let img = UIImage(named: "imageWithoutAlpha")!.alpha(0.5)
let myButton = UIButton()
myButton.setBackgroundImage(img, for: .normal)
How to set the opacity/alpha of a UIImage?
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;
}
Change Alpha of a UIImage Programmatically
You need to change the alpha of the UIImageView
it is contained in, there is no alpha property for UIImage
.
Set alpha for UIView/Image
Assuming titlePicture
is a UIImageView
, you can edit the alpha of it directly:
cell.titlePicture.alpha = (menuItems[indexPath.row] == currentItem) ? 0.6 : 1.0
Tweak the alpha values to your liking. Example output:
alpha = 1.0:
alpha = 0.6:
Change alpha of imageview of UIButton
To conclude the comments on both other answers: subclassing and/or adding another UIImageView
is the simplest choice to archieve persistent, reliant behaviour.
How to add alpha property to an UIImage set with SDWebImage?
Thanks to @Happiehappie 's comment and also this answer from another post I was able to apply the alpha property. Here is the final working code...
posterBackground.sd_setImage(with: URL(string: movieImage!), placeholderImage: UIImage(named: "poster-placeholder"), options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
self.posterBackground.image = image?.alpha(0.15)
})
how to set alpha on Backgroung image using Swift
if you want to set alpha on only background image, then re-create UIImage with changing the alpha value.
if you want to set alpha to entire button, then simply set alpha value to the button.
centerButton.alpha = 0.5
How to make one color transparent on a UIImage?
-(void)changeColor
{
UIImage *temp23=[UIImage imageNamed:@"leaf.png"];
CGImageRef ref1=[self createMask:temp23];
const float colorMasking[6] = {1.0, 2.0, 1.0, 1.0, 1.0, 1.0};
CGImageRef New=CGImageCreateWithMaskingColors(ref1, colorMasking);
UIImage *resultedimage=[UIImage imageWithCGImage:New];
}
-(CGImageRef)createMask:(UIImage*)temp
{
CGImageRef ref=temp.CGImage;
int mWidth=CGImageGetWidth(ref);
int mHeight=CGImageGetHeight(ref);
int count=mWidth*mHeight*4;
void *bufferdata=malloc(count);
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGContextRef cgctx = CGBitmapContextCreate (bufferdata,mWidth,mHeight, 8,mWidth*4, colorSpaceRef, kCGImageAlphaPremultipliedFirst);
CGRect rect = {0,0,mWidth,mHeight};
CGContextDrawImage(cgctx, rect, ref);
bufferdata = CGBitmapContextGetData (cgctx);
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bufferdata, mWidth*mHeight*4, NULL);
CGImageRef savedimageref = CGImageCreate(mWidth,mHeight, 8, 32, mWidth*4, colorSpaceRef, bitmapInfo,provider , NULL, NO, renderingIntent);
CFRelease(colorSpaceRef);
return savedimageref;
}
The above code is tested and I changed the green color to red color by using mask
Related Topics
Swiftyjson - Call Can Throw, But It Is Marked with 'Try' and the Error Is Not Handled
How to Handle Closure Recursivity
Count Elements of Array Matching Condition in Swift
How to Test If Objects Conforming to the Same Protocol Are Identical in Swift Without Casting
Parse.Com Querying User Class (Swift)
Why I Can Change/Reassigned a Constant Value That Instantiated from a Class
Unexpectedly Large Realm File Size
Why Can't I Use a Tuple Constant as a Case in a Switch Statement
Converting a C-Style for Loop That Uses Division for the Step to Swift 3
Know When an Iteration Over Array with Async Method Is Finished
Is This a Good Way to Display Asynchronous Data
How to Write a Function That Will Unwrap a Generic Property in Swift Assuming It Is an Optional Type
Parameters After Opening Bracket
How to Convert Between Related Types Through a Common Initializer
Argument Labels Do Not Match Any Available Overloads
Swift Error: Missing Return in a Function Expected to Return 'String'
Swift: Second Occurrence with Indexof
Showing Cells in Demands in Uicollectionview with Vertical Infinite Scroll