簡體   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