在drawInRect中绘制渐变图层

时间:2017-05-11 10:34:47

标签: ios drawing drawrect cagradientlayer

我正在尝试开发一个costum视图,它的复合版本包含一个包含渐变图层的costum UIView。现在我想在我的新costum视图的drawInRect函数中绘制这个图层,但我不知道该怎么做。

我以前使用渐变图层的custum视图:

 <?php
   $error1 = true;
   $message = $error ? "First error" : ($error1 ? "Second error" : "");
   echo $message;
?>

当我想使用这个视图时,我正在做:

@interface ViewWithGradientLayer : UIView

@property (nonatomic, strong, readonly) CAGradientLayer *layer;

@end

@implementation ViewWithGradientLayer

@dynamic layer;

+ (Class)layerClass {
    return [CAGradientLayer class];
}

@end

现在我已将相同的图层属性添加到我的新自定义视图中,我想在drawInRect中绘制图层:

UIColor *startColor = [UIColor colorWithRed:0.00 green:0.00 blue:0.02 alpha:1.0];
UIColor *endColor = [UIColor clearColor];
self.gradientBackground.layer.colors = @[(__bridge id) endColor.CGColor, (__bridge id) startColor.CGColor];
[self.gradientBackground.layer setStartPoint:CGPointMake(0.5, 0.0)];
[self.gradientBackground.layer setEndPoint:CGPointMake(0.5, 1.0)];

我的复合实现工作正常,但这个没有。我曾尝试过,但是无限循环:

@interface UIBPVCell : UICollectionViewCell

@property (nonatomic, strong, readonly) CAGradientLayer *layer;

@end

@implementation UIBPVCell

@dynamic layer;

+ (Class)layerClass {
    return [CAGradientLayer class];
}

- (void)commonInit {
    UIColor *startColor = [UIColor colorWithRed:0.00 green:0.00 blue:0.02 alpha:1.0];
    UIColor *endColor = [UIColor clearColor];
    self.layer.frame = newsImageRect;
    self.layer.colors = @[(__bridge id) endColor.CGColor, (__bridge id) startColor.CGColor];
    [self.layer setStartPoint:CGPointMake(0.5, 0.0)];
    [self.layer setEndPoint:CGPointMake(0.5, 1.0)];
}

- (instancetype)initWithFrame:(CGRect)frame {
    NSLog(@"UIBPVCell : initWithFrame");
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    //How to draw layer here?
}

更新

我找到了一个类似于已选择答案的答案。这是我的解决方案:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    [self.layer drawInContext:UIGraphicsGetCurrentContext()];
}

1 个答案:

答案 0 :(得分:1)

使用渐变图层或在draw rect中绘制渐变是完全不同的。要在drawRect中绘制渐变,您应该尝试以下内容:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    UIColor *startColor = [UIColor colorWithRed:1.0f green:.0f blue:.0f alpha:1.0f];
    UIColor *endColor = [UIColor colorWithRed:.0f green:1.0f blue:.0f alpha:1.0f];

    NSArray *colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
    CGGradientRef gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), (CFArrayRef)colors, nil);

    CGContextDrawLinearGradient(UIGraphicsGetCurrentContext(), gradient, CGPointMake(0.0f, 0.0f), CGPointMake(self.bounds.size.width, self.bounds.size.height), kCGGradientDrawsBeforeStartLocation|kCGGradientDrawsAfterEndLocation);
}

覆盖drawRect的位置稍低,因此在不创建循环的情况下,您可能无法在其中使用大多数层调用。