2015-03-19 28 views
1

我無法在相同視圖中顯示帶有漸變的2個矩形。我的下面的代碼只顯示第一個矩形。如果我在代碼中省略矩形1,則顯示矩形2。只有組合它纔會顯示矩形1。在IOS中同一視圖上繪製2個帶有漸變的矩形(swift)

我喜歡顯示藍色rectangle1 ...

enter image description here

...和紅色rectangle2具有不同梯度...

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); 


} 

我在做什麼錯?任何幫助?

+0

如何使用一個上下文而不是兩個? – Prontto 2015-03-19 08:39:05

回答

3

UIGraphicsGetCurrentContext()不創建上下文,但只是給你一個當前的參考。 這意味着contextcontext2相同。在context中,您剪切了繪圖區域,以便下一個CGContextAddRect將繪製在裁剪區域之外。

你需要做的是與每個矩形創建代碼之前保存繪製狀態:

CGContextSaveGState(context); 

,並做了第二個矩形代碼

CGContextRestoreGState(context); 

這將確保前恢復裁剪區域在繪製第二個矩形之前被重置。例如:

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

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

非常感謝。這就是解決方案。 – 2015-03-19 08:53:20