2013-06-27 59 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的子视图