gpt4 book ai didi

ios - UIGraphicsGetCurrentContext 问题

转载 作者:行者123 更新时间:2023-11-29 13:11:50 26 4
gpt4 key购买 nike

我正在研究 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com