如何在iPhone sdk中获取彩色图像

如何在iPhone sdk中获取彩色图像,iphone,uiimage,Iphone,Uiimage,我想要如下的东西 UIImage *solid = [UIImage imageWithColor:[UIColor darkGrayColor]]; 创建有关某种颜色的图像 如何在iphonesdk中实现 您可以将颜色绘制到CGContext中,然后从中捕获图像: - (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size { //Create a context of the appropriate size

我想要如下的东西

UIImage *solid = [UIImage imageWithColor:[UIColor darkGrayColor]];
创建有关某种颜色的图像


如何在iphonesdk中实现

您可以将颜色绘制到CGContext中,然后从中捕获图像:

- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size {
  //Create a context of the appropriate size
  UIGraphicsBeginImageContext(size);
  CGContextRef currentContext = UIGraphicsGetCurrentContext();

  //Build a rect of appropriate size at origin 0,0
  CGRect fillRect = CGRectMake(0,0,size.width,size.height);

  //Set the fill color
  CGContextSetFillColorWithColor(currentContext, color.CGColor);

  //Fill the color
  CGContextFillRect(currentContext, fillRect);

  //Snap the picture and close the context
  UIImage *retval = UIGraphicsGetImageFromCurrentImageContext(void);
  UIGraphicsEndImageContext();

  return retval;
}

如果你只是想创建一个实心的长方形,为什么不这样做呢

UIView *solid = [[UIView alloc] initWithFrame:someFrame];
solid.backgroundColor = [UIColor greyColor];
然后将视图添加到要显示纯色的任何子视图中


(当然,只有当这是你想要达到的目标时,你才会这么做。也许你没有)

我认为有一种方法比画画更容易。我在冲浪的时候看到过,但我不记得了。如果有人知道,就把它张贴在这里。绘制它是~ 7行,你可以用一种方便的方法来包装,我不觉得它变得更容易,它不是一个普通的函数。而不是UIGraphicsGetImageFromCurrentImageContext(void);