我有一个UIButton,我希望它显示一个三角形。是否有功能使其成为三角形?因为我不使用UIView类我不知道如何使我的框架成为三角形。
ViewController(m):
- (IBAction)makeTriangle:(id)sender {
UIView *triangle=[[UIView alloc] init];
triangle.frame= CGRectMake(100, 100, 100, 100);
triangle.backgroundColor = [UIColor yellowColor];
[self.view addSubview: triangle];
我是否必须更改我的图层或添加点并将它们连接起来与CGRect形成三角形? 如果我不清楚或不具体添加评论。谢谢!
答案 0 :(得分:2)
按钮是UIView的子类,因此您可以使用CAShape图层将其设置为任何形状。对于下面的代码,我在故事板中添加了一个100 x 100点按钮,并将其类更改为RDButton。
@interface RDButton ()
@property (strong,nonatomic) UIBezierPath *shape;
@end
@implementation RDButton
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.titleEdgeInsets = UIEdgeInsetsMake(30, 0, 0, 0); // move the title down to make it look more centered
self.shape = [UIBezierPath new];
[self.shape moveToPoint:CGPointMake(0,100)];
[self.shape addLineToPoint:CGPointMake(100,100)];
[self.shape addLineToPoint:CGPointMake(50,0)];
[self.shape closePath];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = self.shape.CGPath;
shapeLayer.fillColor = [UIColor yellowColor].CGColor;
shapeLayer.strokeColor = [UIColor blueColor].CGColor;
shapeLayer.lineWidth = 2;
[self.layer addSublayer:shapeLayer];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([self.shape containsPoint:[touches.anyObject locationInView:self]])
[super touchesBegan:touches withEvent:event];
}
touchesBegan:withEvent:override限制按钮在三角形内触摸的动作。
答案 1 :(得分:0)
视图的frame
始终是一个矩形,它是一个矩形。即使您对其应用变换使其不再看起来像矩形,view.frame
属性仍将是一个矩形 - 只是包含您生成的新形状的最小矩形。
因此,如果您希望UIButton看起来像一个三角形,最简单的解决方案可能是将其类型设置为UIButtonTypeCustom
,然后将其图像设置为png,它显示一个三角形并且在其外部是透明的三角形。
然后UIButton本身实际上是矩形,但看起来像一个三角形。
如果你想获得幻想,你也可以自定义触摸传递,这样就无法识别PNG透明部分的触摸(因为我相信它们是默认的),但这可能有点棘手。