2013-06-27 104 views
0

我需要在我的動態創建的視圖中繪製形狀/線條。這是我正在嘗試的代碼,但它並沒有繪製任何東西,雖然意見被添加。在動態創建的UIView中畫線

//loc1 and loc2 are the touch locations on the view used to draw a rect 
UIView *vw = [[UIView alloc] initWithFrame:CGRectMake(loc1.x, loc1.y,loc2.x - loc1.x, loc2.y - loc1.y)]; 
UIGraphicsBeginImageContext(vw.bounds.size); 
CGContextRef ctx = UIGraphicsGetCurrentContext(); 
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0/255.0, 0.0/255.0, 255.0/255.0, 1.0); 
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2); 
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 50, 50)); 
CGContextStrokePath(UIGraphicsGetCurrentContext()); 
UIGraphicsEndImageContext(); 

[mainImageView addSubview:vw]; 
+0

有你補充說,大衆在主視圖? –

+0

你應該在UIView的-drawRect方法中做到這一點。 – Devfly

+0

如果我在UIViewController上,我可以調用drawRect嗎? –

回答

0

不確定你的要求到底是什麼。試試下面的代碼

//loc1 and loc2 are the touch locations on the view used to draw a rect 
[[UIView alloc] initWithFrame:CGRectMake(loc1.x, loc1.y,loc2.x - loc1.x, loc2.y - loc1.y)]; 

UIGraphicsBeginImageContext(vw.bounds.size); 
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0/255.0, 0.0/255.0, 255.0/255.0, 1.0); 
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2); 
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 50, 50)); 
CGContextStrokePath(UIGraphicsGetCurrentContext()); 
CGImageRef result = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext()); 
UIGraphicsEndImageContext(); 

UIImage *image = [UIImage imageWithCGImage:result]; 
CGRect imageFrame = CGRectZero; 
imageFrame.origin = CGPointMake(0, 30); // Change according to your requirement 
imageFrame.size = image.size; 
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageFrame]; 
imageView.image = image; 
[vw addSubview:imageView]; 

[self.view addSubview:vw]; 
+0

正是我需要的。謝謝。 –

1

如果您要在視圖中添加分隔線,您可以像使用UIView一樣使用UIView。使用1或2像素的寬度/高度(取決於您要求的方向)和正確的backgroundColor,您可以創建自己的分隔線,並將其添加到子視圖中。

0

我將繼承的UIView和繪製代碼添加到的drawRect:

- (void)drawRect:(CGRect)rect{ 
CGContextRef ctx = UIGraphicsGetCurrentContext(); 
CGContextSetLineCap(ctx, kCGLineCapRound); 
CGContextSetRGBStrokeColor(ctx, 0.0/255.0, 0.0/255.0, 255.0/255.0, 1.0); 
CGContextSetLineWidth(ctx, 2); 
CGContextAddRect(ctx, CGRectMake(0, 0, 50, 50)); 
CGContextStrokePath(ctx); 
} 

,然後添加自定義的UIView的子視圖