Custom buttons and CALayer

Source: Internet
Author: User

By Matt Long

Address: http://www.cimgf.com/2010/01/28/fun-with-uibuttons-and-core-animation-layers/

At first glance, UIButton basically does not provide what you want from the customization perspective. Therefore, when programmers use IB to set the button's Background attribute, they have to use graphical tools to create the button's Background image. This is also a good solution, but as described in the post, CoreAnimation layers has a simpler method that does not require you to create any images.

1. Change the background color

 

In IB, when you use a Custom Button, you can specify the background color of the Button. But when you run the button, the rounded corner feature is lost, and you only see a square. Because custombutton does not define any default attribute values. You must define them by yourself, so you need to use the Core Animation Layer.

Tip: before writing code, you need to import the QuartzCore framework to the project, and then # import <QuartzCore/QuartzCore. h>. I usually put it in the. pch file.

IB has nothing to do. You can only do it through code. For example, if you want to create a button with a rounded corner and a red background, you need to link the button to the exit of your viewcontroller, in Xcode, modify the following attributes of the button through its layer attribute.

[[Button layer] setCornerRadius: 8.0f];

[[Button layer] setMasksToBounds: YES];

[[Button layer] setBorderWidth: 1.0f];

The above Code sets the Corner radius of the layer to 8.0,-setMasksToBounds: The method tells the layer to hide all layers under it. This is required, so that the rounded corner is not covered.

Finally, set the border to 1.0, and the border of the button is displayed. The default border color is black. You can use the-setBorderColor: method to change it to another color. The parameter uses the CGColorRef type (for example, [[UIColorgreenColor] CGColor] will display the Green Border ).

 

IPhone development skills:Any UIView may be rounded. All uiviews have a root layer. Simply call the-setCornerRadius: And-setMasksToBounds: Methods on the view layer to obtain the rounded corner effect.

You can change the background color in IB or through code. You can use two types of code: layer or setBackgroundColor on UIView:

// CoreAnimation way

[[Button layer] setBackgroundColor: [[UIColor redColor] CGColor];

// UIView way

[Button setBackgroundColor: [UIColorredColor];

The difference is that layer uses the CGColorRef parameter and UIView uses the UIColor parameter.

Ii. Gradient

 

The sample program uses some very bright and fancy color gradient effects. We recommend that you do not learn from me. The transition between the two colors is more natural and better, of course, you can also rely on your personal preferences.

To achieve this gradient, I used CAGradientLayer and added it to the layer tree of the button. In fact, for demonstration, I created a UIButton subclass that encapsulates the creation and drawing of CAGradientLayer. The implementation is as follows.

# Import "ColorfulButton. h"

@ Implementation ColorfulButton

@ Synthesize _ highColor;

@ Synthesize _ lowColor;

@ Synthesize gradientLayer;

-(Void) awakeFromNib;

{

// Initialize the gradient layer

GradientLayer = [[CAGradientLayer alloc] init];

// Set itsbounds to be the same of its parent

[GradientLayersetBounds: [self bounds];

// Centerthe layer inside the parent layer

[GradientLayersetPosition:

CGPointMake ([self bounds]. size. width/2,

[Self bounds]. size. height/2)];

// Insertthe layer at position zero to make sure

// Text of the button is notobscured

[[Self layer] insertSublayer: gradientLayer atIndex: 0];

// Set the layer's corner radius

[[Self layer] setCornerRadius: 8.0f];

// Turn onmasking

[[Self layer] setMasksToBounds: YES];

// Display aborder around the button

// With a 1.0 pixel width

[[Self layer] setBorderWidth: 1.0f];

}

-(Void) drawRect :( CGRect) rect

{

If (_ highColor & _ lowColor ){

// Set the colors for the gradient to

// Two colorsspecified for high and low

[GradientLayer setColors:

[NSArrayarrayWithObjects:

(Id) [_ highColor CGColor],

(Id) [_ lowColor CGColor], nil];

}

[SuperdrawRect: rect];

}

-(Void) setHighColor :( UIColor *) color {

// Set thehigh color and repaint

[Selfset_highColor: color];

[[Selflayer] setNeedsDisplay];

}

-(Void) setLowColor :( UIColor *) color {

// Set thelow color and repaint

[Selfset_lowColor: color];

[[Selflayer] setNeedsDisplay];

}

-(Void) dealloc {

// Releaseour gradient layer

[GradientLayerrelease];

[Superdealloc];

}

@ End

 

Now, I have created a button in IB, set the class to ColorfulButton, and then set an exit in viewcontroller.

 

If you do not set gradient, the button will be rendered with the background color specified in IB. If you want to use the gradient feature, you need to set its corresponding properties in viewcontroller:

-(Void) viewDidLoad {

[SuperviewDidLoad];

[Button1setHighColor: [UIColor redColor];

[Button1setLowColor: [UIColor orangeColor];

[Button2setHighColor: [UIColor blueColor];

[Button2setLowColor: [UIColor lightGrayColor];

[Button3setHighColor: [UIColor yellowColor];

[Button3setLowColor: [UIColor purpleColor];

[Button4setHighColor: [UIColor cyanColor];

[Button4setLowColor: [UIColor magentaColor];

}

There are four buttons in this demo. These buttons are declared in the interface as follows:

# Import <UIKit/UIKit. h>

# Import "ColorfulButton. h"

@ Interface ColorfulButtonsViewController: UIViewController {

IBOutlet ColorfulButton * button1;

IBOutlet ColorfulButton * button2;

IBOutlet ColorfulButton * button3;

IBOutlet ColorfulButton * button4;

}

@ End

CAGrandientLayer supports adding a color array to its colors and automatically uses these colors to make a linear gradient in the form of an even distribution. It also allows you to specify the distribution mode. For simplicity, I only use two colors: highColor and lowColor. If you want to add a more complex color gradient, you can modify the ColorfulButton class.

 

From kmyhy's column

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.