【问题标题】:iOS: Draw shadow within UIViewiOS:在 UIView 中绘制阴影
【发布时间】:2011-11-08 04:31:57
【问题描述】:

我发现了一些很棒的代码,它是UIView 的子类,它用阴影绘制了该视图。然后我可以在任何我想放置阴影的地方使用该视图:

-(void) layoutSubviews {
    CGFloat coloredBoxMargin = 40;
    CGFloat coloredBoxHeight = self.frame.size.height;
    _coloredBoxRect = CGRectMake(coloredBoxMargin, 0, 40, coloredBoxHeight);
}

-(void) drawRect:(CGRect)rect {

    CGColorRef lightColor =  [UIColor colorWithRed:105.0f/255.0f green:179.0f/255.0f blue:216.0f/255.0f alpha:0.8].CGColor;
    CGColorRef shadowColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.4].CGColor;   

    CGContextRef context = UIGraphicsGetCurrentContext();
    // Draw shadow
    CGContextSaveGState(context);
    CGContextSetFillColorWithColor(context, lightColor);
    CGContextSetShadowWithColor(context, CGSizeMake(-13, 0), 10, shadowColor);

    CGContextFillRect(context, _coloredBoxRect);
    CGContextRestoreGState(context);
}

使用以下创建:

UIViewWithShadowRight* verticalLineView2 = [[[UIViewWithShadowRight alloc] initWithFrame:CGRectMake(60, 0, 40 , self.view.frame.size.height)] autorelease];
[verticalLineView2 setBackgroundColor:[UIColor clearColor]];
[verticalLineView2 setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
[verticalLineView2 setClipsToBounds:NO];
[self.view addSubview:verticalLineView2];
[self.view bringSubviewToFront:verticalLineView2];

问题是,阴影是从右向左绘制的,我该如何反转它并从左向右绘制?

【问题讨论】:

    标签: iphone objective-c ios uiview core-graphics


    【解决方案1】:

    13 设为正数而不是负数。即绘制阴影的 x 偏移量,负值在原图左侧,正值在右侧。

    【讨论】:

    • 不,这似乎没有帮助。它使阴影消失。
    • 显示您的代码。这是您正在寻找的实际答案,因此如果您看到不同的结果,可能是由于您在图形上下文中更改了一些其他设置。
    • 乔纳森,我用用于创建视图的代码更新了我的帖子。
    • 绘图仍被裁剪到视图的边界,因此阴影不会绘制到它之外。使视图比其内容更宽。
    【解决方案2】:

    尝试改变这个 CGContextSetShadowWithColor(context, CGSizeMake(-13, 0), 10, shadowColor); 将当前的 x 值 (-13) 替换为右侧的值。

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 2011-02-25
      • 2010-10-22
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      相关资源
      最近更新 更多