用四个角点创建UIView?

时间:2016-10-26 05:42:26

标签: objective-c uiview

如何用四个角创建UIView。

0 = "NSPoint: {79.583483072916664, 54.148963562011716}";  // top left
1 = "NSPoint: {274.96375, 30.877176879882814}"; // top right
2 = "NSPoint: {306.15565104166666, 357.91370518493653}"; // bottom right
3 = "NSPoint: {77.101464843749994, 363.47374218750002}"; // bottom left

我不知道从哪里开始。

4 个答案:

答案 0 :(得分:1)

你的4个角点不是一个矩形 - 一个UIView不能是一个任意的四边形。

要绘制不规则形状,您应该查看Apple使用bezier路径的文档:https://developer.apple.com/library/content/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/BezierPaths/BezierPaths.html

这样的事情:

- (void)drawRect:(CGRect)rect {

    [[UIColor redColor] setStroke];
    [[UIColor yellowColor] setFill];

    UIBezierPath *linePath = [UIBezierPath bezierPath];

    [linePath moveToPoint:CGPointMake(points[0].x, points[0].y)];
    [linePath addLineToPoint:CGPointMake(points[1].x, points[1].y)];
    [linePath addLineToPoint:CGPointMake(points[2].x, points[2].y)];
    [linePath addLineToPoint:CGPointMake(points[3].x, points[3].y)];

    [linePath setLineWidth:LINE_WIDTH];
    [linePath closePath];
}

答案 1 :(得分:1)

你想要的是多边形形状而不是矩形。您无法指定多边形形状进行查看。但是如果您只想在这些点之间显示视图的一部分,则可以在视图上绘制带有这些点的UIBezierPath路径,然后将混合应用于剪辑外部。这是示例代码。

    self.backgroundColor = [UIColor redColor];

    UIBezierPath *aPath = [UIBezierPath bezierPath];
    [aPath moveToPoint:CGPointMake( a.x, a.y)];
    [aPath addLineToPoint:CGPointMake(b.x, b.y)];
    [aPath addLineToPoint:CGPointMake(c.x, c.y)];
    [aPath addLineToPoint:CGPointMake( d.x, d.y)];
    [aPath closePath];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = aPath.CGPath;
    [self.layer setMask:shapeLayer];

答案 2 :(得分:1)

由于您的视图不是常规矩形,因此您需要先绘制一条路径,即BezierPath,然后获取一个形状并将形状强加到视图上。此视图myView的行为与任何其他普通视图一样

    UIView *myView = [[UIView alloc]initWithFrame:self.view.frame];    
    UIBezierPath *linePath = [UIBezierPath bezierPath];

    [linePath moveToPoint:CGPointMake(points[0].x, points[0].y)];
    [linePath addLineToPoint:CGPointMake(points[1].x, points[1].y)];
    [linePath addLineToPoint:CGPointMake(points[2].x, points[2].y)];
    [linePath addLineToPoint:CGPointMake(points[3].x, points[3].y)];
    [linePath closePath];
    CAShapeLayer *shape = [[CAShapeLayer alloc]init];
    [shape setPath:linePath.CGPath];
    myView.layer.mask=shape;
    myView.backgroundColor = [UIColor redColor];
   [self.view addSubview:myView];

输出ScreenShot如下所示:

enter image description here

答案 3 :(得分:0)

您可以将CALayer用于角落,下方的线条会创建一个角落为8的视图。

UIView *myView = [[UIView alloc] init];

myView.layer.masksToBounds = YES;
myView.layer.cornerRadius = 8.0;

或者您可以使用某些框架创建视图,例如

UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(x, y, w, h)];