ios - UIGraphicsGetCurrentContext 问题

标签 ios core-graphics cgcontext

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

我该怎么做?因为当我尝试做某事时,它会删除前一个柱,然后绘制第二个柱,但我需要两者。

代码如下:

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

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

最佳答案

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

假设您的 View 绘图栏充当透明覆盖层,位于其他 UI View 之上,并且仅绘制栏。

为此 View 定义一个数据源,然后在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

在.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

关于ios - UIGraphicsGetCurrentContext 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17106256/

相关文章:

ios - Firebase:使用 swift3 访问子快照

IOS memcpy 纹理到双数组

ios - UIImage 不会显示在屏幕上

iphone - 绘制到 quartz 上下文时,UIImage可拉伸(stretch)ImageWithLeftCapWidth不起作用

iphone - ios 旋转后图像边框变得模糊

objective-c - iOS:持续更新路径的 CGContextStrokePath

ios - uiimageview 刷新所有其他 ImageView

ios - 在应用程序吃午饭时初始化单例类

c# - Xamarin 固定导航栏

ios - 如何强制-drawViewHierarchyInRect :afterScreenUpdates: to take snapshots at @2x resolution?