ios - 在 IOS 的同一 View 上绘制 2 个渐变矩形(快速)

标签 ios swift drawing linear-gradients

我无法在同一个 View 上显示 2 个带有渐变的矩形。我的以下代码仅显示第一个矩形。如果我在代码中省略了 rectangle1,则会显示 rectangle2。只有结合起来,它才会显示 rectangle1。

我喜欢显示蓝色矩形1 ...

enter image description here

...和具有不同渐变的红色矩形2 ...

enter image description here

...同时。

我有以下代码:

func draw_2_gradient_rectangles(){

    let locations: [CGFloat] = [ 0.0, 1.0 ]

    let colorspace = CGColorSpaceCreateDeviceRGB()

    // first rectangle
    let context = UIGraphicsGetCurrentContext()
    let colors = [UIColor.blueColor().CGColor,
        UIColor.whiteColor().CGColor]
    let gradient = CGGradientCreateWithColors(colorspace,
        colors, locations)

    var startPoint1 = CGPoint()
    var endPoint1 =  CGPoint()
    startPoint1.x = 0.0
    startPoint1.y = 10.0
    endPoint1.x = 100;
    endPoint1.y = 10

    let rectangle_main1 = CGRectMake(CGFloat(15), CGFloat(0), CGFloat(100), CGFloat(30));
    CGContextAddRect(context, rectangle_main1);
    CGContextClip(context)
    CGContextDrawLinearGradient(context, gradient, startPoint1, endPoint1, 0)

    // second rectangle
    let context2 = UIGraphicsGetCurrentContext()
    let colors2 = [UIColor.redColor().CGColor,
        UIColor.whiteColor().CGColor]
    let gradient2 = CGGradientCreateWithColors(colorspace,
        colors2, locations)

    var startPoint2 = CGPoint()
    var endPoint2 =  CGPoint()
    startPoint2.x = 100;
    startPoint2.y = 10.0;
    endPoint2.x = 10.0;
    endPoint2.y = 10.9;


    let rectangle_main2 = CGRectMake(CGFloat(15), CGFloat(50), CGFloat(100), CGFloat(30));
    CGContextAddRect(context2, rectangle_main2);
    CGContextClip(context2)
    CGContextDrawLinearGradient(context2, gradient2, startPoint2, endPoint2, 0);


}

我做错了什么?有什么帮助吗?

最佳答案

UIGraphicsGetCurrentContext() 不会创建上下文,而只是为您提供对当前上下文的引用。 这意味着 contextcontext2 相同。在 context 中,您剪切了绘图区域,因此下一个 CGContextAddRect 将在剪切区域之外绘制。

您需要做的是在每个矩形创建代码之前保存绘图状态:

CGContextSaveGState(context);

并在执行第二个矩形代码之前恢复它

CGContextRestoreGState(context);

这将确保在绘制第二个矩形之前重置裁剪区域。例如:

CGContextSaveGState(context);
// Create rectangle1
CGContextRestoreGState(context);

CGContextSaveGState(context);
// Create rectangle2
CGContextRestoreGState(context);

关于ios - 在 IOS 的同一 View 上绘制 2 个渐变矩形(快速),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29139860/

相关文章:

iphone - 如何找到一个月的特定日期?

ios - 在 Swift 编程中将 urlpath 添加到 NSUrl 时得到 nil

ios - 触摸已移动 : How to know when the touch ended?

android - 在 Canvas 上绘制鼠形 (Android)

c# - 如何知道一条线是否与矩形相交

java - 用Swing画图 : general approach

ios - 旋转和导航后状态栏隐藏

ios - UITableView 在单元格选择上更改图像并重置其他图像

更改选择框选项文本的 Jquery - 在 iOS 上不起作用

ios - 连接到 Safari 的 URL