OGeek|极客世界-中国程序员成长平台

标题: ios - drawRect :(CGrect)rect, 目标中未显示阴影 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:03
标题: ios - drawRect :(CGrect)rect, 目标中未显示阴影

我的目标是 1.为我的 View 添加渐变(完成) 2.为我的 View 的底部边缘添加阴影(问题在这里) 我正在做的是:

- (void)drawRectCGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    UIColor *whiteColor         =   [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
    UIColor *lightGrayColor     =   [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0];

    CGRect paperRect            =   self.bounds;

    // Fill with gradient
    [self drawLinearGradient:context for:paperRect start:whiteColor.CGColor end:lightGrayColor.CGColor];

    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
    CGContextSetLineWidth(context, .9);
    CGContextStrokeRect(context, paperRect);

    // Add shadow
    CGContextSetShadowWithColor(context, CGSizeMake(0, self.frame.size.height), 9.0, [UIColor blueColor].CGColor);

}
-(void)drawLinearGradientCGContextRef)context forCGRect)rect startCGColorRef)startColor endCGColorRef)endColor {
    CGColorSpaceRef colorSpace  =   CGColorSpaceCreateDeviceRGB();
    CGFloat locations[]         =   { 0.0, 1.0 };

    NSArray *colors             =   [NSArray arrayWithObjects__bridge id)startColor, (__bridge id)endColor, nil];

    CGGradientRef gradient      =   CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);

    CGPoint startPoint          =   CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint            =   CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

    CGContextSaveGState(context);
    CGContextAddRect(context, rect);
    CGContextClip(context);
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGContextRestoreGState(context);

    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);

}

但是,我得到的是下面没有阴影的图片

我是否在正确的轨道上,但在中间错过了什么?如果您有任何想法,请帮助.. enter image description here



Best Answer-推荐答案


您需要设置阴影属性之前绘制任何应该有阴影的东西。在调用 CGContextStrokeRect 之前先调用 CGContextSetShadowWithColor

此外,偏移量可能不应该像您所做的那样大。阴影偏移量控制阴影与使用该阴影绘制的像素的偏移量,因此除非您希望阴影实际开始时离您的矩形很远,否则您可能只需要一个像素左右的偏移量,例如 CGSizeMake(0.0, 1.0).

关于ios - drawRect CGrect)rect, 目标中未显示阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820205/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4