仅为UIView的一部分设置背景颜色

All*_*Cat 11 uiview ios cgrect uibackgroundcolor

我希望我的UIView的底部(不是一半)与顶部颜色不同.

我想知道我是否应该创建一个CGRect然后着色它?这是沿着正确的轨道吗?

- (void)drawRect:(CGRect)rect { 

    CGRect aRect = CGRectMake(x, y, width, height);

    // Fill the rectangle with grey
    [[UIColor greyColor] setFill];
    UIRectFill( rect );
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*rdo 9

是的,因为你已经覆盖了drawRect方法,这样做.

- (void)drawRect:(CGRect)rect { 

    CGRect topRect = CGRectMake(0, 0, rect.size.width, rect.size.height/2.0);
    // Fill the rectangle with grey
    [[UIColor greyColor] setFill];
    UIRectFill( topRect );

    CGRect bottomRect = CGRectMake(0, rect.size.height/2.0, rect.size.width, rect.size.height/2.0);
    [[UIColor redColor] setFill];
    UIRectFill( bottomRect );

}
Run Code Online (Sandbox Code Playgroud)

根据需要更改框架内的值.


Ima*_*tit 5

使用 Swift 5.1 和 iOS 13,您可以选择以下两种方法之一来解决您的问题。


#1. 使用函数用子类内的实例绘制并填充指定CGRect实例UIColorUIViewUIRectFill(_:)

UIKit提供一个UIRectFill(_:)函数。UIRectFill(_:)有以下声明:

func UIRectFill(_ rect: CGRect)
Run Code Online (Sandbox Code Playgroud)

用当前颜色填充指定的矩形。

以下 Playground 代码显示了如何使用UIRectFill(_:)

import UIKit
import PlaygroundSupport

class CustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor.green
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let bottomRect = CGRect(
            origin: CGPoint(x: rect.origin.x, y: rect.height / 2),
            size: CGSize(width: rect.size.width, height: rect.size.height / 2)
        )
        UIColor.red.set()
        UIRectFill(bottomRect)
    }

}

let view = CustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
PlaygroundPage.current.liveView = view
Run Code Online (Sandbox Code Playgroud)

#2. 使用's方法用子类内的实例绘制并填充指定CGRect实例UIColorUIViewCGContextfill(_:)

CGContext有一个方法叫做fill(_:). fill(_:)有以下声明:

func fill(_ rect: CGRect)
Run Code Online (Sandbox Code Playgroud)

使用当前图形状态下的填充颜色绘制所提供矩形内包含的区域。

以下 Playground 代码显示了如何使用fill(_:)

import UIKit
import PlaygroundSupport

class CustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor.green
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let bottomRect = CGRect(
            origin: CGPoint(x: rect.origin.x, y: rect.height / 2),
            size: CGSize(width: rect.size.width, height: rect.size.height / 2)
        )
        UIColor.red.set()
        guard let context = UIGraphicsGetCurrentContext() else { return }
        context.fill(bottomRect)
    }

}

let view = CustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
PlaygroundPage.current.liveView = view
Run Code Online (Sandbox Code Playgroud)