2015-12-03 146 views
0

我正在設計一個項目的形式。在這個項目中,您選擇一個對象並可以更改顏色或大小,或移動。在Swift中更改UIBezierPath的顏色

開始了應用程序的原型。

我將使用UIBezierPath來繪製形狀的方式,並將使用CAShapeLayer添加到UIView的子圖層。

此代碼繪製例如一種形狀:

let insetRect = CGRect(x: 20, y: 20, width: 100, height: 100) 
let path = UIBezierPath(roundedRect: insetRect, cornerRadius: 30) 
UIColor.redColor().setFill() 
path.fill() 

path.lineWidth = 100 
UIColor.blackColor().setStroke() 
path.stroke() 

let shapeLayer = CAShapeLayer() 
shapeLayer.path = path.CGPath 
shapeLayer.lineWidth = 1.0 

self.view.layer.addSublayer(shapeLayer) 

當應用程序啓動時,在沒有問題創建的形狀。

我希望我可以點擊屏幕並自動改變顏色(隨機)從形狀

另一個問題:形狀是隨機的,他們的矩形,橢圓形,圓角方形。而由於這些表格,我無法直接在View上創建(使用UIBezierPath的原因)。

有些人可以幫助我嗎?我試圖解決這個問題幾個小時,到目前爲止,什麼也沒有發現。

回答

2

除了將bezierPath添加爲子圖層,您可以使用自定義視圖。將貝塞爾路徑座標和顏色傳遞給視圖。保持課堂級別的貝塞爾路徑的實例,並在DrawRect:方法中繪製。

當用戶觸摸控制器中的視圖時,傳遞自定義視圖消息以更改顏色並重繪它。

你可以簡單地通過改變貝塞爾曲線的顏色:

customView.setNeedsDisplay(); 

編輯

CustomView:

yourColor.setStroke(); 

可以使用強制視圖重繪貝塞爾以改變顏色.m

-(id) initWithPath:(UIBezierPath *) path color:(UIColor *) color 
{ 
    if(self = [super init]) 
    { 
     bezierPath = path; 
     pathColor = color; 
    } 
    return self; 
} 

- (void)drawRect:(CGRect)rect 
{ 
    [bezierPath stroke]; 
} 

在控制器,可以初始化爲,

CustomView *customView = [[CustomView alloc] initWithPath:yourBezierPath color:[UIColor redColor]; 
customView.frame = yourFrame; 
[self.view addSubview:customView]; 

變色,

[customView setPathColor:[UIColor greenColor]; 
[customView setNeedsDisplay]; 

希望它能幫助!

+0

您可以發佈示例代碼? – James

+0

@詹姆斯我已經發布了目標c的示例代碼給你一個想法 – NightFury