【问题标题】:Draw squares with Core Graphics or include pngs?使用 Core Graphics 绘制正方形还是包含 png?
【发布时间】:2011-07-26 15:53:48
【问题描述】:

我正在为一个基本上看起来像这样的图表制作图例:

[ ] Line 1
[ ] Line 2
[ ] Line 3

左侧的方框需要与图表上的线条颜色相同。

无论如何,我只需要知道,是用 Core Graphics 绘制方框更快,还是只用 GIMP 为正方形制作一些 png 并包含它们。

【问题讨论】:

  • 在CPU中使用CG更快。重新/开发时间更快地对其进行 png。

标签: iphone ios xcode core-graphics


【解决方案1】:

为每个图例使用 UIView 并将它们的背景颜色设置为您想要的颜色。

【讨论】:

    【解决方案2】:

    这两种方法都足够快,应该不会产生影响。但是,使用 Core Graphics 的优势在于您更加灵活,例如当您以后决定需要其他颜色时。此外,您的应用程序会更小,因为您不必包含 PNG 文件。

    【讨论】:

      【解决方案3】:

      画框很容易!我每天都会使用 Core Graphics,尤其是因为您可以免费获得 Retina 支持。

      从这个例子中可以看出,你可以只使用 UIKit 类来做到这一点:

      // Setup colors
      [myBoxColor setFill];
      [myBoxBorderColor set];
      // Setup a path for the box
      UIBezierPath* path = [UIBezierBath bezierPathWithRect:rectOfTheBox];
      path.lineWidth = 2;
      // Draw!
      [path fill];
      [path stroke];
      

      一个警告;使用路径的边缘作为线条的中心进行描边填充。因此,如果您用 1 点线宽的整数矩形描边路径,您会得到一条模糊的线。

      您可以通过执行以下操作来解决此问题,即您希望边界为 1 点线:

      CGRect strokeRect = UIEdgeInsetsInsetRect(rectOfTheBox, 
                                                UIEdgeInsetsMake(0.5f,0.5f,0.5f,0.5f));
      UIBezierPath* path = [UIBezierPath bezierPathWithRect:strokeRect];
      [path stroke];
      

      【讨论】:

        【解决方案4】:

        在 iOS 上,Core Graphics 使用起来非常简单。在您视图的drawRect: 方法中,只需执行此操作即可绘制一个正方形:

        - (void)drawRect:(CGRect)frame {
            CGContextRef context = UIGraphicsGetCurrentContext();
            CGContextSetRGBFillColor(context, 0.5, 0.5, 0.5, 1); // gray
            CGContextFillRect(context, CGRectMake(10, 10, 20, 20)); // our rect is {10,10,20,20)
            // draw a line
            CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
            CGContextBeginPath(context);
            CGContextMoveToPoint(context, startX, startY);
            CGContextAddLineToPoint(context, endX, endY);
            CGContextStrokePath(context);
        }
        

        希望这会有所帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-23
          • 1970-01-01
          • 2012-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多