user2470111
user2470111

Reputation: 43

UIGraphicsGetCurrentContext issue

I am working on subclass of UIView.In this view i need to UIGraphicsGetCurrentContext.I drawn one horizontal bar and it is working very nice. Now in same view, if user touch anywhere, I need to create another horizontal bar without removing previous bar.

How can i do that? Because when i try to do something it is removing previous bar and then draw second bar but i need both.

Here is code:

    //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);

I am just changing a frame to draw second bar.Please help me.

Upvotes: 1

Views: 1987

Answers (1)

Vinzzz
Vinzzz

Reputation: 11724

When implementing drawRect, context is cleared each time you call setNeedsDisplay. So you have to draw all your bars in a single drawRectcall. Here's an example of how you could achieve this :

Let's say your view drawing bars acts as a transparent overlay, on top of you others UI views, and only draw bars.

Define a datasourcefor this view, then use this data source in drawRect: like this :

In the .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

In the .m

@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

Upvotes: 1

Related Questions