OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 iOS 中动态绘制圆形、椭圆形、矩形等形状? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:17
标题: ios - 如何在 iOS 中动态绘制圆形、椭圆形、矩形等形状?

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



Best Answer-推荐答案


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

怎么办?

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

2. 重写 drawRect(_ 方法,你会在里面完成所有的绘图。

3.将您的形状/线条绘制代码添加到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()
}

关于ios - 如何在 iOS 中动态绘制圆形、椭圆形、矩形等形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43137821/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4