【问题标题】:How to draw shapes like circles, oval, ractangles dynamically in iOS?如何在 iOS 中动态绘制圆形、椭圆形、长方形等形状?
【发布时间】:2017-08-25 13:21:35
【问题描述】:

我有一个 UICollectionView 可以显示圆形、椭圆形、长方形等形状。因此,当我单击 Cell 时,我需要在 UIView 上绘制相同的形状,然后我需要移动并调整通过单击 Cell 绘制的视图的大小。它如何在 iOS 中实现?提前致谢。

【问题讨论】:

  • 你的问题很好,但回答太笼统了
  • 通过thisthis 博客。
  • 你需要阅读 CoreGraphics :)

标签: ios objective-c iphone uiimage core-graphics


【解决方案1】:

如果您使用 UICollectionView,您的可重用单元格将有“层”可供绘制。

怎么办?

1.创建一个UIView 子类并将其放置在您的可重用单元格中。

2. 覆盖drawRect(_:) 方法,您将完成里面的所有绘图。

3. 将您的shape/line drawing code 添加到drawRect 方法。

例如,将UIBezierPath 类用于线条、弧线等。您将能够创建各种形状。

您应该阅读 CoreGraphics API 参考:

https://developer.apple.com/reference/coregraphics

还可以了解LayersContextsdrawRect:

circle 的一个非常基本的示例:

class CircleView: UIView {
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        context.addEllipse(in: rect)
        context.setFillColor(.red.cgColor)
        context.fillPath()
    }
}

并使用 UIBezier 路径绘制线条(矩形、星形等):

override func drawRect(rect: CGRect) {
      var path = UIBezierPath()
      path.moveToPoint(CGPoint(x:<point x>, y:<point y>))
      path.addLineToPoint(CGPoint(x:<next point x>, y:<next point y>))
      point.closePath()

      UIColor.redColor().set()
      point.stroke()
      point.fill()
}

【讨论】:

    【解决方案2】:

    研究贝塞尔路径。这是可能的。希望它对你有用。

    【讨论】:

      【解决方案3】:

      您可以使用 CAShapeLayer。例如。画一个圆圈。

      shapeLayer = [CAShapeLayer layer];
      shapeLayer.frame = aFrame;
      UIBezierPath *spath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:12 startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
      shapeLayer.strokeColor = [UIColor colorWithRed:71/255.0 green:157/255.0 blue:252/255.0 alpha:1].CGColor;
      shapeLayer.path = spath.CGPath;
      shapeLayer.strokeStart = 0;
      shapeLayer.strokeEnd = 0;
      shapeLayer.fillColor = nil;
      shapeLayer.lineWidth = 2;
      [self.layer addSublayer:shapeLayer];
      

      希望对你有帮助

      【讨论】:

      • 你看到了吗UICollectionView
      【解决方案4】:

      您可以使用图层的属性:

      • 角半径
      • 边框宽度
      • 边框颜色

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-07
        • 1970-01-01
        相关资源
        最近更新 更多