objective-c - 是否可以使用 CGContext 绘制图形并将它们保存到 NSMutableArray 中?

标签 objective-c ios nsmutablearray cgcontext cgcontextdrawimage

首先我画图形:

    -(void)drawRect: (CGRect)rect{  

        //Circle
    circle = UIGraphicsGetCurrentContext();  
    CGContextSetFillColorWithColor(circle, [UIColor darkGrayColor].CGColor);
    CGContextFillRect(circle,CGRectMake(10,10, 50, 50));

        //rectangle
    rectangle = UIGraphicsGetCurrentContext();  
    CGContextSetFillColorWithColor(rectangle, [UIColor darkGrayColor].CGColor);
    CGContextFillRect(rectangle, CGRectMake(10, 10, 50, 50));

        //square 
    square = UIGraphicsGetCurrentContext();  
    CGContextSetFillColorWithColor(square, [UIColor darkGrayColor].CGColor);
    CGContextFillRect(square, CGRectMake(100, 100, 25, 25));

        //triangle  
    triangle = UIGraphicsGetCurrentContext(); 
    CGContextSetFillColorWithColor(triangle, [UIColor darkGrayColor].CGColor);
    CGPoint points[6] = { CGPointMake(100, 200), CGPointMake(150, 250),
                              CGPointMake(150, 250), CGPointMake(50, 250),
                              CGPointMake(50, 250), CGPointMake(100, 200) };
    CGContextStrokeLineSegments(triangle, points, 6);

    }

现在我想将图形放入一个数组中:

-(void)viewDidLoad {

grafics = [[NSMutableArray alloc]initWithObjects: circle,rectangle,square,triangle];
[self.navigationItem.title = @"Shape"];
[super viewDidLoad];
}

问题是,我必须进行转换以使对象适合该数组。另一个问题是 UITableViewController 没有将数组加载到行中。 tableview 没有问题,但是处理 CGContext 失败。我做错了什么?

最佳答案

drawRect:UIView 上的一个方法,用于绘制 View 本身,而不是预先创建图形对象。

由于您似乎想要创建形状来存储它们并在以后绘制,因此将形状创建为 UIImage 并使用 UIImageView 绘制它们似乎是合理的。 UIImage 可以直接存储在 NSArray 中。

要创建图像,请执行以下操作(在主队列中;不在 drawRect: 中):

1) 创建位图上下文

UIGraphicsBeginImageContextWithOptions(size, opaque, scale);

2) 获取上下文

CGContextRef context = UIGraphicsGetCurrentContext();

3) 画出你需要的任何东西

4) 将上下文导出到图像中

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

5) 破坏上下文

UIGraphicsEndImageContext();

6) 存储对图像的引用

[yourArray addObject:image];

对您要创建的每个形状重复此操作。

有关详细信息,请参阅 documentation对于上述功能。为了更好地理解在 drawRect: 中绘图和在程序中的任意位置绘图之间的区别,以及一般情况下使用上下文,我建议您阅读 Quartz2D Programming Guide ,尤其是有关图形上下文的部分。

关于objective-c - 是否可以使用 CGContext 绘制图形并将它们保存到 NSMutableArray 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10878141/

相关文章:

ios - 在 ARM/Thumb (IOS) 上解码 BLX 指令

ios - 双击栏按钮项目滚动到顶部

ios - 将一个 NSMuatblearray 添加到另一个 NSMutablearray?

iphone - 如何在 iPhone 3G 上调整大图像的大小而不导致应用程序崩溃?

ios - 使 UIControl 仅接受滑动手势并传递触摸/点击手势

objective-c - 预绑定(bind)消息以避免方法查找

ios - 在 iOS 上使用 Magical Record 进行 TOTAL 查询

iphone - 使用 arrayWithCapacity 比使用数组有什么优势?

ios - 二维数组 Objective-C

ios - 如何在 viewWillAppear 中将 UIScrollView 滚动到底部,当使用自动布局时,没有视觉动画