Scaling down a UIButton's background image when using initWithFrame: - ios

This is the first time I have ever designed an iOS app so I want to make sure I understand this behavior correctly.
I designed a custom bar button icon for a navigation bar in Photoshop. The final image that I saved in Photoshop was 102 x 45, and yes I realize that these dimensions are bigger than the recommended 44x44 in the iOS 7 design guidelines.
Anyways, I placed my image into the asset folder, and then programmatically set the bar button item with the following code:
UIImage* firstButtonImage = [UIImage imageNamed:#"loginbutton1"];
CGRect frame = CGRectMake(0, 0, 102, 45);
UIButton * someButton = [[UIButton alloc] initWithFrame:frame];
[someButton setBackgroundImage:firstButtonImage forState:UIControlStateNormal];
[someButton addTarget:self action:#selector(didTapLoginButton:)
forControlEvents:UIControlEventTouchUpInside];
self.rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navItem.rightBarButtonItem = self.rightBarButton;
As you can see I set the frame's width and height to the exact size of the image. When I first ran the app, I didn't like the image and thought it was too big. So I changed the width and height parameters in this statement:
CGRect frame = CGRectMake(0, 0, 70, 30);
And now the image looks perfect on the iPhone screen. This is on an iPhone 4s.
So my main question is, what is actually happening when I change the frame size? Since the frame is now smaller than the actual image size, does the image just get scaled down automatically to fit inside the frame?

Yes the image get scaled because you are using backgroundImage (not Image). Both images have different behaviors.
Check the Xcode Interface Builder, you can see there, that you can set two images: Image and Background. Background is the UIImage that get scaled for the whole frame of the UIButton.
The UIButton Class Reference allows you to access the imageView of the image (not theimageView of the backgroundImage)
Because you have access to the imageView, you can change the mode of the image with:
[[someButton imageView] setContentMode:UIViewContentModeBottomLeft];
In UIView Class Reference you can check all the UIViewContentModes provided by Apple.
You can check that changing a little bit your code:
[someButton setImage:firstButtonImage forState:UIControlStateNormal];
[[someButton imageView] setContentMode:UIViewContentModeBottomRight];

Related

UIImage on UIButton is blurry

I have been battling this problem for a bit, I want to display a png on a UIButton, but for some reason the image ends up being very blurry both in the simulator and on a physical device. I have tried using all different sized images, all at 326 ppi (verified in xcode), but none have looked correct. I have also tried resizing the image in my app using UIGraphics but the problem persists. Here is the code which sets up the button:
//MIRROR BUTTON
_mirrorButton = [UIButton buttonWithType:UIButtonTypeCustom];
//_mirrorButton.frame = CGRectMake(buttonWidth, 0.0f, buttonWidth, buttonHeight);
_mirrorButton.frame = CGRectMake(64, 0, 64, 50);
UIImage *mirrorImage;
_mirrorButton.backgroundColor = [MessageView getUserColor];
mirrorImage = [UIImage imageNamed:#"mirror.png"];
[_mirrorButton setImage:mirrorImage forState:UIControlStateNormal];
[_mirrorButton addTarget:self action:#selector(mirrorPressed) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_mirrorButton];
Both the UIButton and the image are supposed to have a height of 50 pixels. My UIButton's frame is integral, and the image even has an even pixel width and height (someone said this would help with the centering). Any incite would be much appreciated. Thanks.
From what im reading I presume you might be confusing 50 pixels with 50 points.
The frames in general are measured in points and not in pixels, you can see the difference HERE
So basically, if you use a 50 points high frame, in devices with retina screen you will need an image with 100px high, and then it shouldn't look blurry anymore

UIButton shrinking image?

I am working on an iPad UI and a button on that UI needs to have this image:
http://imgur.com/tVkP8wd
(as a PNG). The button is being declared like this:
CGRect newNoteButtonRect = CGRectMake(0, 0, 69, 43);
UIButton* newNoteButton = [[UIButton alloc] initWithFrame:newNoteButtonRect];
newNoteButton.imageView.contentMode = UIViewContentModeScaleToFill;
[newNoteButton setImage:self.fNewNoteIcon forState:UIControlStateNormal];
where 'fNewNoteIcon' is a UIImage. When the UI comes up, the image is tiny and squished, and almost nothing I do can change that. Any ideas?
The icon is initialized like this:
self.fNewNoteIcon = [UIImage imageNamed:#"New_Note.png"];
In that provided code you haven't specified a UIButton type? Creating a button with a custom image
// Create image
self.fNewNoteIcon = [UIImage imageNamed:#"buttomImage.png"];
// Create rect for button. 0, 0 and size it from image
CGRect newNoteButtonRect = CGRectMake:(0, 0, _fNewNoteIcon.size.width, _fNewNoteIcon.size.height);
// Alloc and init UIButton with type
// Pass in image. Add to subview of view.
UIButton *newNoteButton = [UIButton buttonWithType: UIButtonTypeCustom];
[newNoteButton setImage: _fNewNoteIcon forState: UIControlStateNormal];
[self.view addSubview: newNoteButton];
I type all of this out in SO without compiling so check over but that should get you a UIButton, with the required image at the correct size.
So it looks like if your PNG doesn't have an Alpha channel, then you'll have size issues. I opened the PNG in Photoshop and added an Alpha channel. The image is now properly sized in the iPad!

Building a UIButton out of 3 images

I want to build a UIButton out of 3 images (A,B,C). A and C are stretchable components (depending on the button text) the middle part is fixed.
What is the best way to attach these images to one another? How can I be flexible in the implementation without specifying all origins and widths and so on... Is it necessary to have a surrounding rectangle?
You need to stitch your images together in an image editor to create a single image. Then you'll load this image, and create a resizable version using the UIImage resizableImageWithCapInsets:resizingMode: method. You'll specify UIEdgeInsets that mirror the original widths of your two "end cap" images.
For the button itself you need to make this resizable image the background image of the button. It won't work as a foreground image.
UIImage* bgImage = [[UIImage imageNamed:#"my_bg_image"] resizableImageWithCapInsets: UIEdgeInsetsMake(0, 10, 0, 10)];
UIButton* b = [UIButton buttonWithType: UIButtonTypeCustom];
[b setBackgroundImage: bgImage forState: UIControlStateNormal];
I've had to implement something like this recently.
My strategy was to build what I wanted using UIView objects, and then write the created view to a UIImage.
I'd recommend:-create a container view-create UILabels for the button text, add to container view-for labels A and C, sizeToFit them after they have their text, and then use that information to place the stretchable buttons in the view-once the subviews are positioned, you'll probably want to reset the frame of your container view to make sure it is still correct.
once your view looks the way you want it, write it to an image using:
UIGraphicsBeginImageContextWithOptions(container.frame.size, NO, 0); //or YES if you have no opacity in your images
[container.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
-you can then set this as the image for your UIButton
The best way to do this is to put the 3 images into one file, and use resizableImageWithCapInsets:. See the doco here.
Here's a good tutorial on how to do this.
// Set the button background image
UIImage * buttonImage = [UIImage imageNamed:#"button_resizable.png"];
UIImage * resizableButtonImage = [buttonImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 12, 0, 12)];
[button setBackgroundImage:resizableButtonImage forState:UIControlStateNormal];

UIButton with left+right caps and a middle pattern

How can I create a UIButton with a background image which is composed by:
A fixed left cap
A fixed right cap
A number of middle images placed one after the other to fill all the available space
like in the example below?
EDIT: I did not realize that in the center there are no N repeated images, but only a streched one. See the accepted answer.
As far as I know it cannot be done. What you can do is stretch an image, but you cannot add n middle images.
The code for adding a stretchable image in between is
//Create an image - Where UIEdgeInsets is in top left bottom right
UIImage* buttonImage = [[UIImage imageNamed:#"button.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 16, 0, 16)];
// Create a custom buttom
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(0, 0, 100, buttonImage.size.height);
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[myButton setTitle:#"Button" forState:UIControlStateNormal];
//Add it to view - if it is a view controller self.view
[self addView:myButton];
From Apple's UIImage Class Reference:
"resizableImageWithCapInsets:
You use this method to add cap insets to an image or to change the existing cap insets of an image. [...] During scaling or resizing of the image, areas covered by a cap are not scaled or resized. Instead, the pixel area not covered by the cap in each direction is tiled, left-to-right and top-to-bottom, to resize the image." [emphasis added]
You can read more about it at http://mobiledevelopertips.com/user-interface/ios-5-uiimage-and-resizableimagewithcapinsets.html

iOS - can stretch a UIImageView but not a UIButton?

Behold:
//UIImageView* stretchTest = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image.png"]];
//[self addSubview:stretchTest];
UIButton *stretchTest = [UIButton buttonWithType:UIButtonTypeCustom];
[stretchTest setFrame:CGRectMake(0, 0, 400, 100)];
[stretchTest setBackgroundImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
[self addSubview:stretchTest];
stretchTest.contentStretch = CGRectMake(0.5, 0.5, 0, 0);
stretchTest.contentMode = UIViewContentModeScaleToFill;
CGRect frame = stretchTest.frame;
frame.size.height = 300;
stretchTest.frame = frame;
Using the UIImageView (commented out above), the image stretches appropriately - rounded corners maintain the correct radius, because only the center pixel of the image gets stretched.
Using the UIButton, the image gets stretched incorrectly. The corner radii are not maintained and it gets ugly.
Both UIImageView and UIButton are subclasses of UIView. Why does the button resize differently than the imageView?
You're making assumptions about the way UIButton works. It's not implemented the same way as UIImageView. UIImageView is just a view, with no subviews, and its contents is the image. UIButton is different, and the way it works is a private implementation detail.
If you're trying to stretch an image appropriately on a button, you should use -[UIImage stretchableImageWithLeftCapWidth:topCapHeight:] to get a UIImage that knows how it should be stretched. If you want to stretch just the middle pixel, you can use something like
UIImage *image = [UIImage imageNamed:#"image.png"];
image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
A UIButton has two types of images it can display -- a foreground image and a background image. The background image for a button is expected to replace the button's background texture. As such, it will stretch to fill the entire background. The button's foreground image is expected to be an icon that may or may not display alongside text; it will not stretch. It may shrink if the frame is smaller than the image, but it will not stretch.
A button's foreground and background image can be set in code like this:
// stretchy
[self setBackgroundImage:backgroundImage forState:UIControlStateNormal];
// not stretchy
[self setImage:forgroundImage forState:UIControlStateNormal];
By default, the backgroundImage of a button will use scaleToFill to stretch the image. If you need the image to stretch using cap insets though, you should set them on the image before assigning it to the backgroundImage, like this:
UIImage *image = [UIImage imageNamed:#"bg_image.png"];
/* This assumes your image will have a 1px column and 1px row of pixels
in the horizontal and vertical middle of the image that should be
stretchable. If that's not the case (such as asymetrical buttons)
you need to adjust the caps */
image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2)
topCapHeight:floorf(image.size.height/2)];
[self setBackgroundImage:image forState:UIControlStateNormal];

Resources