Create a UIView with only one diagonal side

旧时模样 提交于 2019-11-30 04:22:33

问题


I need to create a UIView that has the left border inclined with 45 degrees I was wondering,is there a way to acheive this programmatically? Does CATransform3D help me in this case since it’s not really a “3D rotation”?

Edit

Here's an image explaining more my needed output


回答1:


If you just want the shape with no content then you can create a CAShapeLayer and add it to your view's layer. (In fact you can also put content in there using this method but you'll need to alter it a bit).

CAShapeLayer *layer = [CAShapeLayer layer];

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 100)]; // bottom left corner
[path addLineToPoint:CGPointMake(100, 0)]; // top middle
[path addLineToPoint:CGPointMake(300, 0)]; // top right corner
[path addLineToPoint:CGPointMake(300, 100)]; // bottom right corner
[path closePath];

layer.path = path.CGPath;
layer.fillColor = [UIColor blackColor].CGColor;
layer.strokeColor = nil;

[theView.layer addSubLayer:layer];

This doesn't require using drawRect or anything. You will have to change the coordinates based on the values you want.

You can also use a UIView subclass and override drawRect. It requires more work but the UIBezierPath will be pretty much the same.

CALayer is very powerful and used a lot by Apple. For instance the edit canvas in Pages is written almost exclusively using CALayers.




回答2:


Shortest way to achieve this is probably to take the following steps:

  1. Subclass UIView
  2. Override drawRect to provide your custom drawing for the view
  3. In drawRect, use the Core Graphics API, which allows you to draw custom shapes on a drawing context, and offers functions such as rotation or scaling

Here is an overview of the API from the Apple docs.



来源:https://stackoverflow.com/questions/26339943/create-a-uiview-with-only-one-diagonal-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!