简体   繁体   English

自定义iOS UIButton形状

[英]Custom iOS UIButton shape

I'm trying to create a semi circle button as per wireframe. 我正在尝试根据线框创建一个半圆形按钮。

But it's not turning out right. 但这并不是正确的。

This is the code I've written in C#: 这是我用C#编写的代码:

PORCalculatorButton.Layer.CornerRadius = PORCalculatorButton.Layer.Bounds.Width / 2;
PORCalculatorButton.ClipsToBounds = true;
PORCalculatorButton.Layer.MaskedCorners = (CoreAnimation.CACornerMask)3;

There are layout constraints on the button too. 按钮上也有布局约束。

Can anyone tell me where I've gone wrong or if there's a better way? 谁能告诉我哪里出了问题或者是否有更好的方法? I'll accept any answers in ObjC, Swift or C# Thanks. 我将接受ObjC,Swift或C#的任何答案。谢谢。

Try the below Code: 试试下面的代码:

let circlePath = UIBezierPath.init(arcCenter: 
CGPointMake(PORCalculatorButton.bounds.size.width / 2, PORCalculatorButton.bounds.size.height), radius: PORCalculatorButton.bounds.size.height, startAngle: 0.0, endAngle: CGFloat(M_PI), clockwise: false)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.CGPath
PORCalculatorButton.layer.mask = circleShape
  1. Because of layout constraints, your button will resize according to your outer views. 由于布局限制,您的按钮将根据外部视图调整大小。 You need to make sure to apply the layer properties, after your button is rendered, to ensure you have the final frame/bounds, and also re-apply the same properties if the button size changes (say due to rotation etc) 您需要确保在渲染按钮后应用图层属性,以确保拥有最终的帧/边界,并且如果按钮大小发生变化(例如由于旋转等),还需要重新应用相同的属性。
  2. You are trying to clip/mask the button vertically, but you are using width, not height, to calculate corner radius. 您试图垂直修剪/遮盖该按钮,但是您使用的是宽度而非高度来计算拐角半径。 Is this the intended implementation? 这是预期的实现吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM