在自定義控件的時候揽浙,需要給控件的背景圖片設(shè)置透明度逼庞,但是 UI 只提供了不帶透明度的圖片梦鉴,而給控件整體設(shè)置透明度又會影響其子控件的正常顯示,這時候可以利用圖形上下文給 Image 設(shè)置透明度规辱,代碼如下:
+ (UIImage*)imageByApplyingAlpha:(CGFloat)alpha image:(UIImage*)image {
UIGraphicsBeginImageContextWithOptions(image.size,NO,0.0f);
CGContextRefctx =UIGraphicsGetCurrentContext();
CGRectarea =CGRectMake(0,0, image.size.width, image.size.height);
CGContextScaleCTM(ctx,1, -1);
CGContextTranslateCTM(ctx,0, -area.size.height);
CGContextSetBlendMode(ctx,kCGBlendModeMultiply);
CGContextSetAlpha(ctx, alpha);
CGContextDrawImage(ctx, area, image.CGImage);
UIImage*newImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
希望對大家有所幫助。