【问题标题】:Why is drawRect leaving parts of image?为什么drawRect会留下部分图像?
【发布时间】:2014-10-18 03:43:55
【问题描述】:

这是我的情况:

我有一个包含餐馆列表的表格,每个条目都会在使用 drawRect 绘制的记分条上显示一段时间内的检查结果。

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

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

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

我不认为这是缓存自定义单元格的表格行的问题吗? 在这里,一旦 UITableCell 建立单元出列,就会绘制分数条;单元格中的所有其他视图都是正确的,这让我认为问题在于 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 期间,我们尝试清除旧的 scorebarview(如果存在),但代码永远不会找到 DSFScorebarView 类的其他子视图。最后,创建 scorebarView 并将其添加到视图的子视图中。

- (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];

}

scorebarview 是使用 initWithInspections 中的 drawRect 绘制的,并确保 scorebars 的长度不超过 17 个方格(最近的检查)。每次检查都会给出一个绿色 = 低|黄色 = 中等|红色 = 高的正方形,并且在正方形下方绘制年份。

我已将 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 行

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

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

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

- (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) {
  ...

【问题讨论】:

    标签: ios objective-c caching uiview drawrect


    【解决方案1】:

    你已经接管了 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。也许您应该尝试通过子视图进行递归搜索。喜欢:

    - (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

    【讨论】:

    • 你的解释最后被打断了,@HaIR。但这确实告诉了我我的怀疑。您的解决方案有效;但是,当用户点击单元格行时,它会留下一条背景色。 (背景颜色为白色,点击单元格变为灰色)。我需要避免这种情况。
    • 很遗憾,清除单元格中的背景并不会删除下面的图表。
    • 我不想让你到处乱跑,但你试过用 [UIColor clearColor].CGColor 作为背景颜色吗?即 CGContextSetFillColor(ctx, [UIColor clearColor].CGColor);
    • 很高兴现在可以在任何地方运行!我正在使用 [self setBackgroundColor:[UIColor clearColor]];但我也尝试了你的建议: CGFloat backgroundColour[] = {0, 0, 0, 0}; CGContextSetFillColor(ctx, backgroundColor);并得到相同的结果。不过,谢谢。
    • 你就是那个人,@HalR!递归线索正是我所需要的,它有助于识别第二个 scorebarview 并将其删除。非常感谢!
    猜你喜欢
    • 2012-12-02
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 2015-09-28
    • 2013-03-15
    • 2011-03-06
    • 2012-04-07
    相关资源
    最近更新 更多