繁体   English   中英

在动态创建的UIView中画线

[英]Draw line in Dynamically created 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];

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

不确定您的要求到底是什么。 试试下面的代码

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

我将子类化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添加为子视图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM