ios - 在 UIView 上绘制自定义圆角矩形 UIBezierPath

标签 ios iphone swift uiview uibezierpath

我添加了一个 UIView。我有一个类 UIView

我想在其中绘制一个圆角矩形 UIBezierPath,但这是否意味着我必须在我的类中覆盖 UIView 的 drawRect?

我想画这个:

enter image description here

但是我现在如何绘制简单的圆角矩形,在我的类 UIView 中我添加了这个函数:

func roundRect()
{

let rectWidth:CGFloat = 100
let rectHeight:CGFloat = 80

let xf:CGFloat = (self.frame.width  - rectWidth)  / 2
let yf:CGFloat = (self.frame.height - rectHeight) / 2

let ctx: CGContext = UIGraphicsGetCurrentContext()!
ctx.saveGState()

let rect = CGRect(x: xf, y: yf, width: rectWidth, height: rectHeight)
let clipPath: CGPath = UIBezierPath(roundedRect: rect, cornerRadius: rectCornerRadius).cgPath

ctx.addPath(clipPath)

ctx.closePath()
ctx.fillPath()
ctx.restoreGState()
}

最佳答案

在 View 中绘制简单形状的最简单和最有效的方法是向 View 添加一个CAShapeLayer。您可以将它添加为 View 层的子层,或者您可以覆盖 View 的 layerClass() 方法以返回 CAShapeLayer 作为 View 的支持层的类。然后,您可以在 View 的 layoutSubviews() 方法

中将要绘制的路径安装到图层的路径属性中

关于ios - 在 UIView 上绘制自定义圆角矩形 UIBezierPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42785599/

相关文章:

ios - 如何在自定义 UICollectionViewLayout 中仅允许垂直和水平滑动

ios - 图像不适合 UIImageView

ios - 不兼容的指针类型将 'UITapGestureRecognizer *' 发送到类型 'UIView * _Nonnull' 的参数

iphone - 在 iOS 上存储身份验证 token

iphone - 如何访问安装在 gphoto2 ://[usb:001, 003]/的 iPhone?

swift - 如何从 uitableview 单元格中删除单元格

ios - swift 3 网页 View

objective-c - 从传递 float 组的 C 函数调用 Objective C 函数

ios - 以编程方式创建自定义 View ,然后为其设置动画

arrays - Reverse RandomAccessCollection 的 `_base` 属性是什么?