在 uiviewController 的视图中绘制水平线和垂直线



我有一个带有一些图像的UIViewController。我需要在图像之间画一些水平线和垂直线。实际上,它就像一个层次视图。添加带有背景色的子视图是最好的方法吗?

您有三种基本方法:

  1. 在自定义UIView子类中使用QuartzCore并覆盖drawRect:
  2. 设置包含每个图像的UIImageView层属性的borderWidth和borderColor
  3. 为水平线创建高度为1、为垂直线创建宽度为1的UIViews,设置视图的backgroundColor并将其添加为子视图

3可能是最容易实现的,但不是最优雅的,1在内存方面是最强大的,因为您也可以使用drawInRect将图像绘制到相同的图形上下文中。这会将视图层次折叠为单个视图。

您可以使用上面回答的层来完成,或者因为您只需要行,所以使用UIViews

就像这个

for(i=0;i<numberOfLine*heightofImage;i+=heightOfImage) {
    UIView *horizontalLine=[[UIView alloc]initWithFrame:CGRectMake(x, i, height, 1)];
    [self.view addSubView:horizontalLine];
}

希望对有所帮助

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIView *verticalLine = [[UIView alloc] initWithFrame:CGRectMake(roundf(self.view.bounds.size.width / 2), 0.0, 1.0, self.view.bounds.size.height)];
    verticalLine.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
    verticalLine.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin;
    [self.view addSubview:verticalLine];
    UIView *horizontalLine = [[UIView alloc] initWithFrame:CGRectMake(0.0, roundf(self.view.bounds.size.height / 2), self.view.bounds.size.width, 1.0)];
    horizontalLine.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.5];
    horizontalLine.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    [self.view addSubview:horizontalLine];
}

我使用了Magic Bullet Dave发布的第三个选项,效果很好。这是代码:

UIView *borderBottom = [[UIView alloc] initWithFrame:CGRectMake(0.0, 10, widthDesired, 1.0)];
borderBottom.backgroundColor = [UIColor grayColor];
[myView addSubview:borderBottom];

如果你想画一条垂直线,你只需使用宽度1,然后使用所需的高度。

最新更新