【问题标题】:Making a triangle in a UIView with a CGRect Frame使用 CGRect 框架在 UIView 中制作三角形
【发布时间】:2014-12-22 02:39:47
【问题描述】:

您好,我正在制作一款游戏,需要在底部设置一个尖峰,我决定通过 UIView 和碰撞来实现。我正在快速编码。

我目前有一个正方形:

        //Object Setup
        let square = UIView(frame: CGRect(x:100, y:100, width: 100, height: 100))
        square.backgroundColor = UIColor.purpleColor()
        view.addSubview(square)

我想要一个三角形,我确实有一个可以用于三角形的图像,但是图像是正方形的,所以当它接触图像边界而不是实际的三角形边界时,肯定会发生碰撞,请建议如何做有图像或我是如何得到方形的。

谢谢

亚历克斯

【问题讨论】:

  • 您是否考虑过在您的游戏中使用 SpriteKit?真正的“形状匹配”物理和碰撞使用 SpriteKit 非常容易,但是当你创建游戏时 UIKit 会很快达到它的极限

标签: ios uiview swift cgrect


【解决方案1】:

步骤:

  1. 创建一个名为TriangleView 的子类UIView 的新文件
  2. 将其粘贴到 TriangleView 类中
  3. 通过XIB 或以编程方式添加TriangleView

import UIKit

class TriangleView: UIView {

    override func draw(_ rect: CGRect) {

        // Get Height and Width
        let layerHeight = layer.frame.height
        let layerWidth = layer.frame.width

        // Create Path
        let bezierPath = UIBezierPath()

        // Draw Points
        bezierPath.move(to: CGPoint(x: 0, y: layerHeight))
        bezierPath.addLine(to: CGPoint(x: layerWidth, y: layerHeight))
        bezierPath.addLine(to: CGPoint(x: layerWidth / 2, y: 0))
        bezierPath.addLine(to: CGPoint(x: 0, y: layerHeight))
        bezierPath.close()

        // Apply Color
        UIColor.green.setFill()
        bezierPath.fill()

        // Mask to Path
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = bezierPath.cgPath
        layer.mask = shapeLayer
    }
}

结果:

【讨论】:

  • Swift 2 编译器可能会告诉您,您的大部分vars 应该是lets,因为您不会在创建它们之后对其进行变异。这包括beizerPath,因为你改变了Objective-C对象,而不是指针。
  • 如何使用此方法传入自定义参数或颜色?
  • @AndrewAnthonyGerst 看看这个 - stackoverflow.com/a/24263296/2415921 只需将Swift Extension 发送到UIView。您可以在 1 个类中进行扩展,也可以从任何其他类访问它!
  • @MikeMilla 感谢麦克的及时回复!我确实想通了。我创建了一个新的构造函数,所以我可以传入自定义参数。 let triangleView = TriangleView(frame: CGRectMake(0.0, 0.0, 50.0, 50.0), dir: "down", color: UIColor.orangeColor())你知道有没有办法在三角形周围添加阴影?
  • 工作就像一个魅力。
【解决方案2】:

这里有教程:

http://jamesonquave.com/blog/drawing-custom-views-with-swift-andrew-vanwagoner/

使用如下代码:

func drawPlayPathTo(context: CGContextRef, boundedBy rect: CGRect) {
  CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
  CGContextMoveToPoint(context, rect.width / 4, rect.height / 4)
  CGContextAddLineToPoint(context, rect.width * 3 / 4, rect.height / 2)
  CGContextAddLineToPoint(context, rect.width / 4, rect.height * 3 / 4)
  CGContextAddLineToPoint(context, rect.width / 4, rect.height / 4)
  CGContextFillPath(context)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 2019-02-27
    • 2012-11-26
    相关资源
    最近更新 更多