如何重用drawRect代码?

时间:2015-06-11 13:11:12

标签: ios objective-c cocoa-touch

我想添加一个图形效果/渐变,我在UIView的类中。我在界面构建器中选择了该类。

但是现在我想将它用于桌面视图。它不允许我在界面构建器中为tableview选择相同的类。

我不想复制我的绘图代码,我该如何移动它?

- (void)drawRect:(CGRect)rect {
    // Drawing code.
}

2 个答案:

答案 0 :(得分:1)

而是覆盖drawRect,您可以使用内置图层阴影方法(在您的子类中):

- (void)awakeFromNib {
    self.yourTableView.layer.shadowOffset = CGSizeMake(2.0, 2.0);
    self.yourTableView.layer.shadowColor= [UIColor blackColor].CGColor;
}

答案 1 :(得分:1)

我建议将drawRect代码保存到图像中,然后使用UIImageView而不是自定义视图。这样它只会被绘制一次。我为UIImage做了一个便利类别,我觉得它非常整洁。

@implementation UIImage (CustomImage)

+ (UIImage *)imageOfSize:(CGSize)size withBlock:(void (^)(CGContextRef context))drawingBlock{
    UIGraphicsBeginImageContextWithOptions(size, 0, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);
    drawingBlock(context);
    UIGraphicsPopContext();
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
} 

你这样使用它。

UIImage *myComplicatedPaintImage = [UIImage imageOfSize:tableViewCell.bounds.size withBlock:^(CGContextRef context) {

    //No need to fetch context, it is provided as block argument
    CGContextBeginPath(context);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextMoveToPoint(context, 123, 456);
    CGContextAddLineToPoint(context,789,1011);
    CGContextStrokePath(context);
}

然后只保留对该图像的引用,并将所有单元格添加到imageView中。

UIImageView *imageView = [UIImageView alloc]initWithFrame:tableViewCell.bounds];
imageView.image = myComplicatedPaintImage;
[self.view insertSubview:imageView atIndex:0];