【问题标题】:Drawing Polygons in Swift在 Swift 中绘制多边形
【发布时间】:2015-01-04 17:57:10
【问题描述】:

当用户点击它时,我需要突出显示不规则形状。我关于如何做到这一点的想法是绘制一个与形状匹配的多边形,用颜色填充它并更改不透明度以使其半透明。不幸的是,我找不到有关如何执行此操作的任何信息。本质上,我想绘制填充的多边形,将其覆盖到我的地图上,然后能够关闭(或隐藏)它。我怎样才能做到这一点?

【问题讨论】:

  • 看看这个用 Objective C 编写的 mac 应用程序。你可能会从中得到一个想法。
  • 您可以在 drawRect: 中绘制形状:(使用 UIBezierPath),或者创建一个视图并将贝塞尔路径添加到您添加到视图层的 CAShapeLayer。

标签: ios swift drawing polygons


【解决方案1】:

您可能想使用CAShapeLayer。这是一个演示:

import XCPlayground
import UIKit
import CoreText

let view = UIView(frame: CGRectMake(0, 0, 300, 300))
XCPShowView("view", view)

let imageView = UIImageView(image: UIImage(named: "profile.jpg"))
imageView.frame = view.bounds
imageView.contentMode = UIViewContentMode.ScaleAspectFill
view.addSubview(imageView)

let shape = CAShapeLayer()
view.layer.addSublayer(shape)
shape.opacity = 0.5
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
shape.strokeColor = UIColor(hue: 0.786, saturation: 0.79, brightness: 0.53, alpha: 1.0).CGColor
shape.fillColor = UIColor(hue: 0.786, saturation: 0.15, brightness: 0.89, alpha: 1.0).CGColor

let path = UIBezierPath()
path.moveToPoint(CGPointMake(120, 20))
path.addLineToPoint(CGPointMake(230, 90))
path.addLineToPoint(CGPointMake(240, 250))
path.addLineToPoint(CGPointMake(40, 280))
path.addLineToPoint(CGPointMake(100, 150))
path.closePath()
shape.path = path.CGPath

结果:

斯威夫特 3:

let shape = CAShapeLayer()
cell.layer.addSublayer(shape)
shape.opacity = 0.5
shape.lineWidth = 2
shape.lineJoin = kCALineJoinMiter
shape.strokeColor = UIColor(hue: 0.786, saturation: 0.79, brightness: 0.53, alpha: 1.0).cgColor
shape.fillColor = UIColor(hue: 0.786, saturation: 0.15, brightness: 0.89, alpha: 1.0).cgColor

 let path = UIBezierPath()
 path.move(to: CGPoint(x: 120, y: 20))
 path.addLine(to: CGPoint(x: 230, y: 90))
 path.addLine(to: CGPoint(x: 240, y: 250))
 path.addLine(to: CGPoint(x: 100, y: 150))
 path.close()
 shape.path = path.cgPath

【讨论】:

  • 谢谢你。这很棒。您能否提供使用拖动功能处理/添加更多行到路径中的方法
  • 我们如何使用平移手势将整个形状或一个角点移动到特定点?
猜你喜欢
  • 1970-01-01
  • 2011-12-30
  • 2012-01-07
  • 2016-05-20
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多