ios - 为什么 drawRect 会留下部分图像?

标签 ios objective-c caching uiview drawrect

这是我的案例:

我有一个包含餐厅列表的表格,每个条目都在使用 drawRect 绘制的记分栏上显示随时间变化的检查结果。

当用户向下滚动表格然后向上滚动时,会显示带有黄色和红色方 block 的记分栏,之前的记分栏会选择这些方 block 。日期也被绘制到以前的记分栏中。

我的问题在于摆脱旧方 block 。它们不应该在每次调用 drawRect 时都被删除吗?

我在下面放了三张图片,希望能解释我的意思。

我不认为这是表行缓存自定义单元格的问题? 一旦 UITableCell 建立单元格出队,就会在此处绘制得分条;单元格中的所有其他 View 都是正确的,这让我认为问题在于 drawRect 未能清除图形上下文。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.row < self.establishments.count) {
      return [self establishmentCellForIndexPath:indexPath];
  } else if (self._noResultsFound) {
      return [self noResultsCell];
  } else {
      return [self loadingCell];
  }
}

- (UITableViewCell *)establishmentCellForIndexPath:(NSIndexPath *)indexPath {

  static NSString *CellIdentifier = @"EstablishmentCell";

  DSFEstablishment *establishment = [self.establishments objectAtIndex:[indexPath row]];

  DSFEstablishmentCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  [cell setEstablishment:establishment];
  [cell updateCellContent];

  return cell;
}

在 updateCellContent 期间,我们尝试清除旧的 scorebarviews(如果存在),但代码从未找到 DSFScorebarView 类的其他 subview 。最后,scorebarView 被创建并添加到 View 的 subview 中。

- (void)updateCellContent {
NSLog(@"updateCellContent: %@", self.establishment.latestName);

self.name.text = self.establishment.latestName;
self.address.text = self.establishment.address;
self.type.text = self.establishment.latestType;
if (self.establishment.distance) {
    self.distance.text = [NSString stringWithFormat:@"%.2f km", self.establishment.distance];
} else {
    self.distance.text = @"";
}

// Clear out old scorebarView if exists
for (UIView *view in self.subviews) {
    if ([view isKindOfClass:[DSFScorebarView class]]) {
        NSLog(@">>>removeFromSuperview");
        [view removeFromSuperview];
    }
}

DSFScorebarView *scorebarView = [[DSFScorebarView alloc] initWithInspections:self.establishment.inspections];
[self addSubview:scorebarView];

得分栏 View 是在 initWithInspections 中使用 drawRect 绘制的,并确保得分栏的长度不超过 17 个方格(最近的检查)。每次检查都有一个绿色=低|黄色=中等|红色=高的方 block ,年份画在方 block 下方。

我已经设置了 self.clearsContextBeforeDrawing = YES,但它并没有解决问题。

// Custom init method
- (id)initWithInspections:(NSArray *)inspections {
CGRect scorebarFrame = CGRectMake(20, 38, 273, 22);
if ((self = [super initWithFrame:scorebarFrame])) {
    self.inspections = inspections;

    self.clearsContextBeforeDrawing = YES;

    [self setBackgroundColor:[UIColor clearColor]];
}
return self;
}

- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();

float xOffset = 0; // Keep track of position of next box -- start at 1
float yOffset = 0; // Fixed Y offset. Adjust to match shadows
NSString *previousYear = nil;
UIFont *yearFont = [UIFont fontWithName:@"PFTempestaFiveCompressed" size:8.0];

// take subset/slice of inspections. only the last 17, so it will fit on screen.
int inspections_count = (int)[self.inspections count];

int startIndex = inspections_count > 17 ? inspections_count - 17 - 1 : 0;
int subarrayLength = inspections_count > 17 ? 17 : inspections_count;
NSArray *inspectionsSlice = [self.inspections subarrayWithRange:NSMakeRange(startIndex, subarrayLength)];

for (id inspection in inspectionsSlice) {

    // Top of box
    NSMutableArray *pos0RGBA = [inspection colorForStatusAtPositionRGBA:0];
    CGFloat topColor[] = ...
    CGContextSetFillColor(ctx, topColor);
    CGRect box_top = CGRectMake(xOffset, yOffset, kScoreBoxWidth, kScoreBoxHeight / 2);
    CGContextAddRect(ctx, box_top);
    CGContextFillPath(ctx);

    // Bottom of box
    NSMutableArray *pos1RGBA = [inspection colorForStatusAtPositionRGBA:1];
    CGFloat bottomColor[] = ...
    CGContextSetFillColor(ctx, bottomColor);
    CGRect box_bottom = CGRectMake(xOffset, kScoreBoxHeight / 2 + yOffset, kScoreBoxWidth, kScoreBoxHeight / 2);
    CGContextAddRect(ctx, box_bottom);
    CGContextFillPath(ctx);

    // Year Text
    NSString *theYear = [inspection dateYear];
    if (![theYear isEqualToString:previousYear]) {
        CGFloat *yearColor = ...
        CGContextSetFillColor(ctx, yearColor);
        // +/- 1/2 adjustments are positioning tweaks
        CGRect yearRect = CGRectMake(xOffset+1, yOffset+kScoreBoxHeight-2, kScoreBoxWidth+50, kScoreBoxHeight);
        [theYear drawInRect:yearRect withFont:yearFont];
        previousYear = theYear;
    }

    xOffset += kScoreBoxWidth + kScoreBoxGap;
}
  • 加载表格,绘制 4 行

Starting position

  • 用户向下滚动;又绘制了 8 行

enter image description here

  • 用户滚动回到顶部; Grace Market/Maple Pizza(第 2 行)的记分栏已更改。

enter image description here

在下面实现@HaIR 的解决方案后,在点击表格行后,我在灰色背景上得到了一条白色 strip 。在添加额外宽度以“遮盖”年线之后,它非常难看。

- (void)drawRect:(CGRect)rect {
  ...
  CGFloat backgroundColour[] = {1.0, 1.0, 1.0, 1.0};
  CGContextSetFillColor(ctx, backgroundColour);
  CGRect fullBox = CGRectMake(xOffset, yOffset, kScoreBoxWidth * 17, 2 * (kScoreBoxHeight-2));
  CGContextAddRect(ctx, fullBox);
  CGContextFillPath(ctx);

  for (id inspection in inspectionsSlice) {
  ...

grey tablerow with scorebar graph and white strip

最佳答案

您已经接管了 DrawRect,因此它只会执行您在 dra 中手动执行的操作

在上面绘制任何内容之前,用背景色填充整个条形区域。

您正在重复使用单元格,因此,例如,您在 Grace Market/Maple Plaza 的第二个版本下方显示了 Turf Hotel Restaurant 图表。

CGContextSetFillColor(ctx, yourBackgroundColor);
CGRect fullBox = CGRectMake(xOffset, yOffset, kScoreBoxWidth * 17, kScoreBoxHeight);
CGContextAddRect(ctx, fullBox);
CGContextFillPath(ctx);

如果您只是清除单元格中的背景而不是使用背景颜色。然后:

CGContextClearRect(context, rect);

在您的 DrawRect 开头可能更合适。

修订:

仔细查看您的问题,根本问题是您没有找到并删除旧的 DSFScoreboardView。也许您应该尝试通过 subview 进行递归搜索。喜欢:

- (void)logViewHierarchy {
    NSLog(@"%@", self);
    for (UIView *subview in self.subviews) {
        //look right here for your DSFScorebarView's
        [subview logViewHierarchy];
    }
}
@end

// In your implementation
[myView logViewHierarchy];

(取自https://stackoverflow.com/a/2746508/793607)

关于ios - 为什么 drawRect 会留下部分图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25478319/

相关文章:

ios - 应用程序因生物识别而关闭时崩溃

iphone - 在 iOS 中解析 Intuit XML 响应

ios - 需要帮助设置两个等宽的按钮,并排自动布局

caching - 在获取新数据时在 react-native 应用程序上使用中继缓存数据

ios - 快速按下按钮时在下一个 View 中显示不同的图像?

ios - 在 UicollectionViewCell 中更新 CollectionView 的大小

ios - dispatch_queue_set_specific 与获取当前队列

objective-c - 在Interface Builder中设计一个NSView子类然后实例化它?

c++ - 性能:一次做所有事情,还是每个操作循环几次?

java - 请求 hazelcast jcache 提供程序时 HazelcastClientCachingProvider 类未找到异常