【问题标题】:Draw circle on rectangle在矩形上画圆
【发布时间】:2013-03-27 21:59:28
【问题描述】:

我有 UIView 类,在方法中我想绘制第一个矩形,有时是圆形

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

    if ([WhatToDraw isEqual:@"Fields"]) {
        [self DrawField:context];
            }
    if ([WhatToDraw isEqual:@"Ball"]) {
        [self DrawBall:context x:20 y:20];
    }

}

-(void)DrawBall:(CGContextRef)context x:(float) x y:(float) y
{
    UIGraphicsPushContext(context);
    CGRect  rect = CGRectMake(x, y, 25, 25);
    CGContextClearRect(context, rect);
    CGContextFillEllipseInRect(context, rect);
}

-(void)DrawField:(CGContextRef)context 
{

    columns = 6;
    float offset = 5;
    float boardWidth = self.frame.size.width;
    float allOffset = (columns + 2) * offset;
    float currentX = 10;
    float currentWidth = (boardWidth - allOffset) / columns;
    float currentHeight = currentWidth;
    self.fieldsArray = [[NSMutableArray alloc] init];
    //create a new dynamic button board
    for (int columnIndex = 0; columnIndex<columns; columnIndex++) {
        float currentY = offset;
        for (int rowIndex=0; rowIndex<columns; rowIndex++) {
            UIGraphicsPushContext(context);
            //create new field


            CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
            CGContextBeginPath(context);
            CGRect rect = CGRectMake(currentX, currentY, currentWidth, currentHeight);
            CGContextAddRect(context, rect);
            CGContextFillPath(context);

            currentY = currentY + offset + currentHeight;
        }
        currentX = currentX + offset + currentWidth;
    }  
}

我也有方法改变画什么

-(void)Draw:(NSString*)Thing
{
    self.WhatToDraw = Thing;
    [self setNeedsDisplay];
}

绘制矩形(字段)是可以的,但是当我单击按钮绘制圆形时,所有矩形都消失了,只绘制了圆形。 如何在现有矩形上画圆?

【问题讨论】:

  • 这是一个离题但非常重要的部分:Objective-C Naming Conventions
  • sry,我是目标 c.. 的初学者。:/
  • 没有问题,有时间就读一读。 :)

标签: iphone ios objective-c uiview drawrect


【解决方案1】:

问题

您的问题是,当UIView 重绘由setNeedsDisplaysetNeedsDisplayInRect 标记的区域时,它将在执行您的绘图代码之前完全清除该区域。这意味着除非您在 drawRect 内的单个绘图操作中同时绘制矩形和圆形,否则您将永远不会在您选择重绘的区域中看到两者都绘制,无论是使用 setNeedsDisplay 的整个视图边界还是特定的带有setNeedsDisplayInRect的区域。

解决方案

没有理由不能每次都在drawRect 中同时绘制矩形和圆形,并通过仅使用setNeedsDisplayInRect 重绘必要的区域来优化绘图性能。

或者,您可以使用CALayers 分解内容,并将矩形放在一层,圆形放在另一层。这将允许您利用Core Animation 的动画功能。核心动画提供了一种简单有效的方式来操作屏幕上的图层,其中包含移动、调整大小、更改颜色等隐式动画。

【讨论】:

    【解决方案2】:

    我的猜测,你的 DrawBall 方法中的 CGContextClearRect 调用是矩形消失的责任......来自 Apple 文档:如果提供的上下文是窗口或位图上下文,Quartz 有效地清除矩形。 em>

    【讨论】:

    • 我删除了它,没有任何变化。但是不是setNeedsDisplay的问题导致重绘所有uiview?
    • 我明白了...对不起,我不明白您的代码流程。您是否考虑过不同的解决方案?您应该使用子图层而不是绘制矩形/圆形:这样您可以轻松添加/删除它们,更改 z-order 等等......
    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 2020-04-14
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多