首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从子视图获取CGContextRef

从子视图获取CGContextRef
EN

Stack Overflow用户
提问于 2012-11-23 19:01:16
回答 1查看 2K关注 0票数 0

我正在使用UIGraphicsGetCurrentContext()为UI元素创建渐变背景,但我猜我误解了绘制的位置。我希望绘图发生在一个子视图上,但它却发生在视图本身。

我认为问题是当我使用UIGraphicsGetCurrentContext()时,我得到了视图的CGContextRef,所以这就是绘图发生的地方。我想做的是让绘图发生在子视图上,这样我就可以将它与其他相关的子视图一起淡入淡出。这可以做到吗?或者我需要为背景层创建另一个UIView子类吗?

这是我正在使用的代码的简化,我的目标是能够淡入和淡出topBar中的背景渐变,同时使InterfaceControlsView视图可见。

代码语言:javascript
复制
@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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-23 19:30:02

要为子视图创建渐变bg,您不需要创建子类,请使用渐变图层。希望这能有所帮助

代码语言:javascript
复制
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];
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13527731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档