ios - 如何在 Swift 的未知宽度和高度的 View 中将 UIBezierPath 椭圆居中?

标签 ios swift uiview uibezierpath

我在自定义 UIView 中使用绘制函数来创建自定义纹理。问题是宽度和高度由 UIStackView 决定。当我创建 View 时,我使用 CustomView(frame: CGRect(x: 0, y: 0, width: 50, height: 50, color: color) 如果实际宽度和高度在自定义 UIView 的时间使用绘制函数。有没有办法保证 UIBezierPath 在 UIStackView 给定的范围内居中?

import Foundation 
import UIKit 
class CustomView: UIView {

        let color: UIColor

        required init(coder aDecoder: NSCoder) {
            color = UIColor()
            super.init(coder: aDecoder)!
        }
        init(frame: CGRect, color: UIColor) {
            self.color = color
            super.init(frame: frame)
            self.backgroundColor = UIColor.init(hexString: CustomColors.pale_blue)
        }

        override func draw(_ rect: CGRect) {

            color.setFill()
            color.setStroke()
            let width = Int(rect.size.width)
            let height = Int(rect.size.height)
            let yValue = Int(rect.origin.y)
            let xValue = Int(rect.origin.x)
            let rectBottom = UIBezierPath(rect: CGRect(x: xValue , y: yValue + height - (height/4), width: width, height: height/4))
            let ovalTop = UIBezierPath(ovalIn: CGRect(x: xValue + (width/4), y:yValue + (height/3), width: width/2, height: height/2))
            rectBottom.stroke()
            rectBottom.fill()
            ovalTop.fill()
            ovalTop.stroke()
        } 
}

最佳答案

在调用绘制方法时,布局已经发生。只需看看 draw() 中的 self.bounds。 需要明确的是,不要查看传递给绘制的矩形来确定您的几何形状。如果您只想重绘需要更新的位,则只能使用该矩形。

关于ios - 如何在 Swift 的未知宽度和高度的 View 中将 UIBezierPath 椭圆居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42755192/

相关文章:

ios - 使用 dispatch_block 崩溃

ios - 无法导入 UIKit

json - Alamofire 嵌套 JSON 序列化器

iphone - 带虚线的 UIView

ios - 在 UITabBar iOS 中更改项目颜色

iphone - iOS 模拟器——摆脱 "reset/don' t 重置“窗口?

java - iOS 调用 [NSDate timeIntervalSinceNow] 的 Android/Java 等价物是什么?

ios - 取消 ONLongPressGesture

iphone - 如何进行键值观察并在 UIView 的框架上获取 KVO 回调?

ios - 初始化 UIView 对象时的 dispatch_async