【问题标题】:Put shadow to a rectangle (drawRect:(CGRect)rect)将阴影放在矩形上 (drawRect:(CGRect)rect)
【发布时间】:2014-07-08 15:50:56
【问题描述】:

我用这段代码做了一个矩形,它可以工作:

- (void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextAddRect(context, CGRectMake(60, 60, 100, 1));
    CGContextStrokePath(context);
}

但现在我想放一个阴影,我尝试了这个:

NSShadow* theShadow = [[NSShadow alloc] init];
[theShadow setShadowOffset:NSMakeSize(10.0, -10.0)];
[theShadow setShadowBlurRadius:4.0];

但是 xcode 告诉我NSMakeSize : Sending 'int' to parameter of incompatible type 'CGSize'

关于阴影的正确形式是什么? 谢谢!!

【问题讨论】:

  • 试试CGSizeMake而不是NSMakeSize
  • 我改变了你评论我,现在xcode不告诉我错误,但没有出现阴影
  • CGContextSetShadow()怎么样?
  • 实际上我也在尝试:CGColorRef shadowColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.5].CGColor; CGContextSetShadowWithColor(context, CGSizeMake(1, -1), 2, shadowColor);
  • 但是,,,什么都没有发生

标签: objective-c drawrect cgrectmake


【解决方案1】:

您应该在绘制应该有阴影的对象的函数之前调用CGContextSetShadow(...) 函数。完整代码如下:

- (void)drawRect:(CGRect)rect {
    // define constants
    const CGFloat shadowBlur = 5.0f;
    const CGSize shadowOffset = CGSizeMake(10.0f, 10.0f);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);

    // Setup shadow parameters. Everithyng you draw after this line will be with shadow
    // To turn shadow off invoke CGContextSetShadowWithColor(...) with NULL for CGColorRef parameter.
    CGContextSetShadow(context, shadowOffset, shadowBlur);

    CGRect rectForShadow = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width - shadowOffset.width - shadowBlur, rect.size.height - shadowOffset.height - shadowBlur);
    CGContextAddRect(context, rectForShadow);
    CGContextStrokePath(context);
}

备注:

我注意到您向CGContextAddRect(context, CGRectMake(60, 60, 100, 1)); 提供了一些随机值。您应该只在通过rect 参数接收到的矩形内绘制。

【讨论】:

  • 噢噢噢!!!现在我可以看到阴影了,非常感谢.. 好的,您的评论有道理,所以它取决于矩形?
  • @user2958588,根据苹果文档:You should limit any drawing to the rectangle specified in the rect parameter. 我认为这样做的原因是为了提高渲染性能。请注意,矩形大小和原点可能与您的视图框架不同,因为视图的某些部分可能已经渲染,因此 iOS 可能只请求重新渲染一部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
相关资源
最近更新 更多