在动态创建的UIView中绘制线条

时间:2013-06-27 11:39:12

标签: ios uiview uiimageview uigraphicscontext

我需要在动态创建的视图中绘制形状/线条。这是我正在尝试的代码,但是虽然添加了视图,但它并没有绘制任何内容。

//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];

3 个答案:

答案 0 :(得分:1)

如果要在视图上添加分隔符/行,可以像使用UIView一样使用。使用1或2像素的宽度/高度(取决于您要求的方向)和正确的backgroundColor,您可以创建自己的分隔符,并将其添加到子视图中。

答案 1 :(得分: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];

答案 2 :(得分: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添加为子视图