使UIImageView IOS变暗

时间:2013-01-20 21:39:49

标签: ios xcode

我想要做的是让UIImageView变暗,以便在图像顶部显示按钮和视图。我想给它在用户使用Facebook分享的ios6时给出的效果。它背后的所有内容都变得更暗,但它是可见的。我尝试使用:

    UIImage *maskedImage = [self darkenImage:image toLevel:0.5];

- (UIImage *)darkenImage:(UIImage *)image toLevel:(CGFloat)level
{
// Create a temporary view to act as a darkening layer
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
UIView *tempView = [[UIView alloc] initWithFrame:frame];
tempView.backgroundColor = [UIColor blackColor];
tempView.alpha = level;

// Draw the image into a new graphics context
UIGraphicsBeginImageContext(frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[image drawInRect:frame];

// Flip the context vertically so we can draw the dark layer via a mask that
// aligns with the image's alpha pixels (Quartz uses flipped coordinates)
CGContextTranslateCTM(context, 0, frame.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextClipToMask(context, frame, image.CGImage);
[tempView.layer renderInContext:context];

// Produce a new image from this context
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *toReturn = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
UIGraphicsEndImageContext();
return toReturn;
}

但它没有达到我想要的效果。它会改变颜色,而我只是希望它变得更暗,就像你使用ios facebook分享一样,背景变暗。这可能吗?

1 个答案:

答案 0 :(得分:8)

要制作UIView,其所有内容和子视图,更暗,您只需在其上绘制另一个UIView,它全部为黑色并具有Alpha透明度,以便此“屏蔽视图”的黑色与内容相混合查看下面。如果Alpha透明度为0.5,则下面的所有内容看起来都会变暗50%。

要获得淡入淡出效果,只需使用“屏蔽视图”的转换:

// Make the view 100% transparent before you put it into your view hierarchy.
[myView setAlpha:0];

// Layout the view to shield all the content you want to darken.
// Give it the correct size & position and make sure is "higher" in the view
// hierarchy than your other content.
...code goes here...

// Now fade the view from 100% alpha to 50% alpha:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[myView setAlpha:0.5];
[UIView commitAnimations];

您可以根据需要更改动画持续时间以使淡入淡出更慢或更快。如果您没有设置任何动画持续时间,则使用默认持续时间(我猜这是Facebook共享的情况)。