我正在使用UIGraphicsGetCurrentContext()为UI元素创建渐变背景,但我猜我误解了绘制的位置。我希望绘图发生在一个子视图上,但它却发生在视图本身。
我认为问题是当我使用UIGraphicsGetCurrentContext()时,我得到了视图的CGContextRef,所以这就是绘图发生的地方。我想做的是让绘图发生在子视图上,这样我就可以将它与其他相关的子视图一起淡入淡出。这可以做到吗?或者我需要为背景层创建另一个UIView子类吗?
这是我正在使用的代码的简化,我的目标是能够淡入和淡出topBar中的背景渐变,同时使InterfaceControlsView视图可见。
@implementation InterfaceControlsView
- (id)initWithFrame:(CGRect)frame
{
topBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, 20.0, self.frame.size.width, 45.0)];
/* etc. */
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = topBar.frame; // topBar is a subview
CGContextSaveGState(context);
CGContextAddRect(context, rect);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
/* etc. */
}
@end发布于 2012-11-23 19:30:02
要为子视图创建渐变bg,您不需要创建子类,请使用渐变图层。希望这能有所帮助
CALayer *layer = _button.layer;
layer.borderWidth = 1.0f;
layer.borderColor = [UIColor lightGrayColor].CGColor;
CAGradientLayer *gLayer = [CAGradientLayer layer];
[gLayer setName:@"gradient"];
gLayer.frame = layer.bounds;
gLayer.colors = [NSArray arrayWithObjects:
(id)[UIColor colorWithRed:26.0/255.0 green:94.0/255.0 blue:74.0/255.0 alpha:1.0].CGColor,
(id)[UIColor colorWithRed:23.0/255.0 green:59.0/255.0 blue:37.0/255.0 alpha:1.0].CGColor,
nil];
[layer addSublayer:gLayer];https://stackoverflow.com/questions/13527731
复制相似问题