在矩形上绘制圆圈

时间:2013-03-27 21:59:28

标签: iphone ios objective-c uiview drawrect

我有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];
}

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

2 个答案:

答案 0 :(得分:4)

问题

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

解决方案

没有理由不能在setNeedsDisplayInRect内每次都不能同时绘制矩形和圆圈,只需通过重新绘制drawRect所需的区域来优化绘图的性能。

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

答案 1 :(得分:0)

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