VRMaskColoredButton 1.1.0

VRMaskColoredButton 1.1.0

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布日期上次发布2016年8月
SPM支持 SPM

Ivan Rublev 维护。



  • Ivan Rublev

VRMaskColoredButton

这是一个 UIButton 类的子类,允许您独立设置按钮图像的形状和颜色。更适合平面设计。

通过灰度图像定义按钮图像和背景图像的形状。为必要的 UIControlState 设置颜色。然后按钮控件通过组合灰度掩码图像和设置颜色为每个状态生成彩色图像。

使用项目中的矢量 PDF 资产作为掩码图像。在编译时,XCode 会为所有设备显示分辨率生成必要的图像。这样,您可以在项目中为每个按钮拥有两个或甚至一个图像文件。

VRMaskColoredButton 可以通过 Interface Builder 完全配置。

安装

VRMaskColoredButton 通过 CocoaPods 提供。要安装,只需将以下行添加到 Podfile 中

pod "VRMaskColoredButton"

使用

VRMaskColoredButton 可以通过 storyboards 或仅代码使用。以下是常见步骤:

为图像和背景图像制作掩码,作为矢量资产。这些应该是为 @1x 分辨率准备的 PDF,具有以下一般特征:

  • 分辨率:每英寸 72 个像素。
  • 启用层。
  • PDF 兼容性:Acrobat 8(PDF 1.7)

将准备好的图像添加到您项目中的资产库。有关详细信息,请参阅这篇文章

使用 Storyboard

  1. 打开 storyboard,并在所需视图中添加一个按钮控件。选择添加的按钮,打开 Identity Inspector,并在自定义类部分中将类字段和模块字段的值为 VRMaskColoredButton 设置。

  2. 打开 Attributes Inspector,将按钮类型更改为自定义。

  3. 在按钮部分将 Image 和 Background 属性设置为之前添加的掩码资产。

  4. 在遮罩色按钮部分中将 Normal Color 和 Normal Background Color 属性设置为所需颜色。

    按钮将以选定颜色绘制图像显示。

如果您需要,可以更改 Highlighted、Selected 或 Selected+Highlighted 颜色属性。对于该状态,还有 Selected+Highlighted Image 和 Background Image 属性可用于设置图像。

通过代码

Swift

let button = VRMaskColoredButton(frame: CGRectMake(0, 0, 44, 44))
button.setImage(UIImage(named: "btn_image"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "btn_background_image"), forState: .Normal)
button.setImageColor(UIColor(red: 0, green: 1.0, blue: 44/255.0, alpha: 1.0), forState: .Normal)
button.setBackgroundImageColor(UIColor(red: 5/255.0, green: 224/255.0, blue: 1.0, alpha: 1.0), forState: .Normal)

Objective-C

VRMaskColoredButton *button = [[VRMaskColoredButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
[button setImage:[UIImage imageNamed:@"btn_image"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"btn_background_image"] forState:UIControlStateNormal];
[button setImageColor:[UIColor colorWithRed:0 green:1.0 blue:44/255.0 alpha:1.0] forState:UIControlStateNormal];
[button setBackgroundImageColor:[UIColor colorWithRed:5/255.0 green:224/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];

有关进一步详情,请参阅示例项目。

UIImage 扩展

除了按钮类之外,您还可以在 UIImage 遮罩对象上使用 imageByApplyingColor 函数来应用颜色。您可以指定背景颜色或背景图片来填充遮罩的背景。如果不指定背景参数值,则默认为透明颜色。

let maskImage = UIImage(named: "btn_image")!
let assembledImage0 = maskImage.imageByApplyingColor(UIColor.greenColor())
let assembledImage1 = maskImage.imageByApplyingColor(UIColor.greenColor(), backgroundColor: UIColor.blueColor())
let assembledImage2 = maskImage.imageByApplyingColor(UIColor.greenColor(), mergeWithBackgroundImage: UIImage(named: "complicated_background_image"))

要求

  • iOS 8.0 或更高版本。
  • Xcode 7 或更高版本。

作者

Ivan Rublev, [email protected]

许可

VRMaskColoredButton遵循MIT协议许可使用。详见LICENSE文件获取更多信息。