简体   繁体   English

如何在Swift中创建具有自定义形状的UIButton?

[英]How to create UIButton with custom shape in Swift?

I need to create button like this 我需要像这样创建按钮 在此处输入图片说明

and the change the background programmatically like this 然后像这样以编程方式更改背景 在此处输入图片说明

and like this 像这样 在此处输入图片说明

I can not use images for different states of a button because each time I have different text on it. 我不能将图像用于按钮的不同状态,因为每次按钮上都有不同的文本。

What to start from ? 从什么开始? I tried to understand CoreGraphics and CoreAnimation but there is too small amount of examples and tutorials so my attempts didn't give me any success. 我试图了解CoreGraphics和CoreAnimation,但是示例和教程数量太少,因此我的尝试没有给我带来任何成功。

You can , and should, use an image for this. 可以并且应该为此使用图像。 UIKit has a method resizableImageWithCapInsets that creates resizable images. UIKit具有一种可重新调整大小的图像的方法resizableImageWithCapInsets You feed it a minimum sized image and the system stretches it to fit the desired size. 您将其送入最小尺寸的图像,然后系统将其拉伸以适合所需的尺寸。 It looks like your image is fixed in height, which is good since you can't do smooth gradients with this technique. 看起来图像的高度是固定的,这很好,因为使用此技术无法进行平滑的渐变。

UIButton s are composed of a background image and title text, so you can use an image for the background shapes ( setBackgroundImage(_:forState:) ), and then change the text using setTitle(_:forState:) . UIButton由背景图像和标题文本组成,因此您可以将图像用于背景形状( setBackgroundImage(_:forState:) ),然后使用setTitle(_:forState:)更改文本。

However, you can still use Core Graphics for this, and there are benefits to doing so, such as the fact that it reduces the number of rendered assets in your app bundle. 但是,您仍然可以为此使用Core Graphics,这样做有很多好处,例如,它减少了应用程序包中渲染资产的数量。 For this, probably the best approach is to create a CAShapeLayer with a path constructed from a UIBezierPath , and then render it into a graphics context. 对于这一点,可能是最好的方法是创建一个CAShapeLayer从构建的路径UIBezierPath ,然后将其渲染成一个图形上下文。 From this context, you can pull out a UIImage instance, and treat it just the same as an image loaded from a JPEG or PNG asset (that is, set it as the buttons background image using setBackgroundImage(_:forState:) ). 在此上下文中,您可以拉出UIImage实例,并将其与从JPEG或PNG资产加载的图像相同(即,使用setBackgroundImage(_:forState:)将其设置为按钮背景图像)。

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

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