UIImage drawinrect方法不绘制图像

时间:2013-12-08 22:02:08

标签: ios objective-c uiimage

我创建了一个cust UIView类,以便我可以显示Map对象的内容。经过大量研究,我仍然无法确定下面的方法为什么不绘制任何东西:

- (void)drawRect:(CGRect)rect
{
    if(_map!=nil){
        UIGraphicsBeginImageContext(rect.size);
        UIImage *img = [UIImage imageNamed:@"grass"];
        float w =  rect.size.width / _map.width;
        float h =  rect.size.height / _map.height;
        for(int x=0; x<_map.width; x++){
            for(int y=0; y<_map.height; y++){
                Tile *tile = [_map getTileAtX:x Y:y];
                UIImage *img = [UIImage imageNamed:NSStringFromTileType(tile.type)];
                [img drawInRect:CGRectMake(x*w, y*h, w, h)];
            }
        }
        UIGraphicsEndImageContext();
    }
}

我打电话给[mapView setNeedsDisplay]来刷新UIView。

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

在您的代码中UIGraphicsBeginImageContext(...)将新图像上下文推送到视图的上下文之上,drawInRect:将图像绘制到此新上下文中。 UIGraphicsEndImageContext()弹出图像上下文,使其内容失效。当您想要创建 UIImage时,通常会使用推送图像上下文,而不是在您需要其内容绘制到上下文中时。

如果您想查看图片,请删除UIGraphicsBeginImageContextUIGraphicsEndImageContext来电。

相关问题