Jon*_*an. 6 iphone objective-c layer uiimageview
我需要在触摸时使UIImageView变暗,几乎就像跳板(主屏幕)上的图标一样.
我是否应该添加0.5 alpha和黑色背景的UIView.这看起来很笨拙.我应该使用图层还是其他东西(CALayers).
我会让UIImageView处理图像的实际绘制,但是将图像切换到预先变暗的图像.这是我用来生成alpha维护的暗图像的一些代码:
+ (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();
[tempView release];
return toReturn;
}
Run Code Online (Sandbox Code Playgroud)
如何子类化 UIView 并添加 UIImage ivar(称为图像)?然后你可以重写 -drawRect: 类似的东西,前提是你有一个在触摸时设置的名为按下的布尔 ivar。
- (void)drawRect:(CGRect)rect
{
[image drawAtPoint:(CGPointMake(0.0, 0.0))];
// if pressed, fill rect with dark translucent color
if (pressed)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextSetRGBFillColor(ctx, 0.5, 0.5, 0.5, 0.5);
CGContextFillRect(ctx, rect);
CGContextRestoreGState(ctx);
}
}
Run Code Online (Sandbox Code Playgroud)
您可能想要尝试上面的 RGBA 值。当然,非矩形形状需要更多的工作 - 就像 CGMutablePathRef。
| 归档时间: |
|
| 查看次数: |
3484 次 |
| 最近记录: |