1

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

    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 共享时,背景变暗。这可能吗?

4

1 回答 1

8

要使 UIView 及其所有内容和子视图更暗,您只需在其上绘制另一个全黑且具有 alpha 透明度的 UIView,以便此“屏蔽视图”的黑色与下面视图的内容混合。如果 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 分享时就是这种情况)。

于 2013-01-21T00:19:29.760 回答