创建三角形UIView

时间:2015-04-21 13:31:34

标签: ios objective-c xcode

我需要创建UIView形状的标签示例:

enter image description here

我的第二个选择是创建一个标准的UIView(Square)并在他身边添加另一个小三角视图。

但我不知道如何创建这个三角视图。

3 个答案:

答案 0 :(得分:1)

您可以使用UIBezierPath执行此操作,这是使用它的示例代码。它不会与您的预期结果相同,但您可以使用您的积分绘制

UIBezierPath* trianglePath = [UIBezierPath bezierPath];
[trianglePath moveToPoint:CGPointMake(0, view3.frame.size.height-100)];
[trianglePath addLineToPoint:CGPointMake(view3.frame.size.width/2,100)];
[trianglePath addLineToPoint:CGPointMake(view3.frame.size.width, view2.frame.size.height)];
[trianglePath closePath];

CAShapeLayer *triangleMaskLayer = [CAShapeLayer layer];
[triangleMaskLayer setPath:trianglePath.CGPath];

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, size.width, size.height)];

view.backgroundColor = [UIColor colorWithWhite:.75 alpha:1];
view.layer.mask = triangleMaskLayer;
[self.view addSubview:view];

答案 1 :(得分:0)

如果你想创建一个自定义视图,你可以试试这个:你需要把它作为你的UIView的类。

- (void)drawRect:(CGRect)frame   
  {
//// Color Declarations
UIColor* color = [UIColor colorWithRed: 0.318 green: 0.472 blue: 0.866 alpha: 1];

//// Rectangle Drawing
UIBezierPath* rectanglePath = UIBezierPath.bezierPath;
[rectanglePath moveToPoint: CGPointMake(CGRectGetMinX(frame), CGRectGetMinY(frame) + 120)];
[rectanglePath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 171, CGRectGetMinY(frame) + 120)];
[rectanglePath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 240, CGRectGetMinY(frame) + 67)];
[rectanglePath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 240, CGRectGetMinY(frame) + 66)];
[rectanglePath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 167, CGRectGetMinY(frame))];
[rectanglePath addLineToPoint: CGPointMake(CGRectGetMinX(frame), CGRectGetMinY(frame))];
[rectanglePath addLineToPoint: CGPointMake(CGRectGetMinX(frame), CGRectGetMinY(frame) + 120)];
[rectanglePath closePath];
[color setFill];
[rectanglePath fill];
}

答案 2 :(得分:0)

您可以尝试使用此代码并根据您的要求更改点。

[[self view] setBackgroundColor:[UIColor blueColor]];

CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path,NULL,0.0,100);
CGPathAddLineToPoint(path, NULL, 160.0f, 100.0f);
CGPathAddLineToPoint(path, NULL, 160.0f, 100.0f);
CGPathAddLineToPoint(path, NULL, 200.0f, 150.0f);
CGPathAddLineToPoint(path, NULL, 160.0f, 200.0f);
CGPathAddLineToPoint(path, NULL, 0.0f, 200.0f);
CGPathAddLineToPoint(path, NULL, 0.0f, 480.0f);
CGPathAddLineToPoint(path, NULL, 0.0f, 0.0f);


CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setPath:path];
[shapeLayer setFillColor:[[UIColor redColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
[shapeLayer setBounds:CGRectMake(0.0f, 0.0f, 160.0f, 480)];
[shapeLayer setAnchorPoint:CGPointMake(0.0f, 0.0f)];
[shapeLayer setPosition:CGPointMake(0.0f, 0.0f)];
[[[self view] layer] addSublayer:shapeLayer];

CGPathRelease(path);
相关问题