Objective c 显示三角形的按钮
我有一个UIButton,我希望它显示一个三角形。有没有一个函数可以把它变成三角形?由于我没有使用UIView类,我不知道如何使我的框架成为三角形Objective c 显示三角形的按钮,objective-c,Objective C,我有一个UIButton,我希望它显示一个三角形。有没有一个函数可以把它变成三角形?由于我没有使用UIView类,我不知道如何使我的框架成为三角形 ViewController(m): - (IBAction)makeTriangle:(id)sender { UIView *triangle=[[UIView alloc] init]; triangle.frame= CGRectMake(100, 100, 100, 100); triangle.backgroundColor = [UI
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生成三角形?
如果我不清楚或不具体,请添加评论。谢谢大家! 视图的
帧始终是矩形,即矩形。即使对其应用变换,使其不再看起来像矩形,view.frame
属性仍将是一个矩形,即包含您生成的新形状的最小矩形
因此,如果您希望UIButton看起来像三角形,最简单的解决方案可能是将其类型设置为UIButtonTypeCustom
,然后将其图像设置为png,该图像显示三角形,并且在三角形外部是透明的
然后UIButton本身实际上是矩形,但看起来像三角形
如果你想喜欢,你也可以自定义触摸传递,这样PNG透明部分的触摸就不会被识别(我相信默认情况下会被识别),但这可能有点棘手。按钮是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];
}
触摸开始:withEvent:override将按钮的操作限制为在三角形内触摸。我不确定您的意思“将其图像设置为显示三角形的png,并在三角形外透明”我的意思是,创建一个png,该png除了覆盖其部分区域的不透明三角形外,是完全透明的。然后对状态执行[button setImage:[UIImage ImageName:@“triange.png”]操作:UIControlStateNormal]代码>