1

我正在研究 UIView 的子类。在这个视图中,我需要 UIGraphicsGetCurrentContext。我画了一个水平条,它工作得非常好。现在在同一个视图中,如果用户触摸任何地方,我需要创建另一个水平条而不删除前一个条。

我怎样才能做到这一点?因为当我尝试做某事时,它会删除前一个栏,然后绘制第二个栏,但我需要两者。

这是代码:

    //set frame for bar
    CGRect frameDays;
    frameDays.origin.x = prevDayWidth;
    frameDays.origin.y = heightBar;
    frameDays.size.height = heightOfBar;
    frameDays.size.width = distanceBetweenDays;

    UIColor* color = [monthColorArray objectAtIndex:i%12];
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextSetLineWidth(context, lineWidth);
    CGContextSetStrokeColorWithColor(context, borderColor.CGColor);

    CGContextFillRect(context, frameDays);
    CGContextStrokeRect(context, frameDays);

我只是改变一个框架来绘制第二条。请帮助我。

4

1 回答 1

1

实施时drawRect,每次调用时都会清除上下文setNeedsDisplay。因此,您必须在一次drawRect调用中绘制所有条形图。这是一个如何实现这一目标的示例:

假设您的视图绘图条充当透明覆盖层,在您的其他 UI 视图之上,并且仅绘制条。

datasource为这个视图定义一个,然后drawRect:像这样使用这个数据源:

在.h

@protocol BarOverlayDatasource <NSObject>

- (NSUInteger)numberOfBars;
- (CGRect)barFrameForIndex:(NSUInteger)index;
- (UIColor *)barColorForIndex:(NSUInteger)index;

@end


@interface BarsOverlayView : UIView

@property (nonatomic, weak) id<BarOverlayDatasource> datasource;


@end

在他们中

@implementation BarsOverlayView

#define NEMarkedViewCrossSize 7


- (void)drawRect:(CGRect)rect
{
    if (self.datasource) {
        CGContextRef context = UIGraphicsGetCurrentContext();

        //drawing settings
        UIColor* barColor = nil;
        CGRect barFrame = CGrectZero;
        CGContextSetLineWidth(context, lineWidth);

        CGContextSetStrokeColorWithColor(context, borderColor.CGColor);


        NSUInteger barCount = [self.datasource numberOfBars];

        //repeat drawing for each 'bar'
        for (NSUInteger i =0; i < barCount; i++) {
            //retrieve data defining bar position, 
            // I chose CGRect for the example, but maybe a single CGPoint would be
            //enough to computer each barFrame
            barFrame = [self.datasource barFrameForIndex:i];
            barColor = [self.datasource barColorForIndex:i]

            CGContextSetFillColorWithColor(context, barColor.CGColor);

            CGContextFillRect(context, barFrame);
            CGContextStrokeRect(context, barFrame);



        }


    }
}


@end
于 2013-06-14T10:48:12.020 回答