iOS change UIButton frame to it's image frame weird error - ios

I have a strange error when trying to change UIButton's frame.
I am trying to do the following:
UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
UIImage *image = [UIImage imageNamed:imageName];
btn.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[btn setImage:image forState:UIControlStateNormal];
and I an image editor I see that image size is 35x37, but image.size.width / height gives me 16.
What am I doing wrong?
PS: If I double the image.size.width, then the button's frame seems ok. I thought that both image size and UIView frame are in points.

Related

UIButton changes image created in code when in highlighted state

I have two buttons. They both have the same image except the fact that one of the images is flipped. I don't want to have an excess image in the bundle of my app if it's possible to create image programmatically so i create my buttons like this:
UIImage *forwardImage = [UIImage imageNamed:rewind_btn_img];
UIImage *rewindImage = [UIImage imageWithCGImage:forwardImage.CGImage
scale:forwardImage.scale
orientation:UIImageOrientationUpMirrored];
NSArray *images = #[rewindImage, forwardImage];
for (int i = 0; i < 2; i++)
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = images[i];
btn.frame = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
btn.center = CGPointMake(self.playButton.center.x + (i == 0 ? - 80.f : 80.f) * TGScaleMultiplier, self.playButton.center.y);
btn.tag = i + 1;
[btn setBackgroundImage:image forState:UIControlStateNormal];
[btn addTarget:self action:#selector(rewindButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
The problem is that when i press the button whose image is rewindImage it shows the original image, flipped to the other side. Am i doing something incorrectly here? Is there any workaround?
Not sure exactly why that UIImage:imageWithCGImage is flaky but I tried another method for mirroring the image and when applied to the button it works great. So get rid of the UIImage:imageWithCGImage line and use this:
UIImage *rewindImageBase = [UIImage imageNamed:rewind_btn_img];
UIGraphicsBeginImageContext(rewindImageBase.size);
CGContextRef current_context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(current_context, rewindImageBase.size.width, 0);
CGContextScaleCTM(current_context, -1.0, 1.0);
[rewindImageBase drawInRect:CGRectMake(0, 0, rewindImageBase.size.width, rewindImageBase.size.height)];
UIImage *rewindImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
That should do it.
if it initially looks right, but changes when you press it, Try setting the image for all button states, or at least for the normal state and the selected state.
[btn setBackgroundImage:image forState:UIControlStateNormal];
[btn setBackgroundImage:image forState:UIControlStateSelected];
you could also try setting the showsTouchWhenHighlited but the first way should work
[btn setShowsTouchWhenHighlighted:NO];
EDIT: try also setting the highlighted state, this works for me
[btn setBackgroundImage:image forState:UIControlStateHighlighted];

How to set background for UIButtons with dynamic width?

I have 3 button images named edit_category_left_up,edit_category_middle_up and edit_category_right_up
I have written code to create buttons with dynamic width now I need to set background of these button like this image below using the above 3 images
This is my current code to create dynamic buttons
-(void) addDynamicButtonsForCategories
{
_adcImage.hidden=YES;
_makeADCLabel.hidden=YES;
float x=0; float y=0; float frameHeight=_subADCView.frame.size.height;
NSString *titleString=#"";
for(int i = 0; i < 15; i++)
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
if (i<1)
{
[btn setFrame:CGRectMake(0, 0, 39, 39)];
[btn setImage:[UIImage imageNamed:#"addcategory_up.png"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:#"addcategory_down.png"] forState:UIControlStateHighlighted];
x = x + btn.frame.size.width+10; y=y+btn.frame.origin.y;
[btn setTitle:titleString forState: UIControlStateNormal];
[btn setTag:i];
}
else
{
titleString = [titleString stringByAppendingString:[NSString stringWithFormat:#"%d",i]]; // get button title
CGSize fontSize = [titleString sizeWithFont:[UIFont systemFontOfSize:12.0]];
CGRect currentFrame = btn.frame;
CGRect buttonFrame = CGRectMake(x, y, fontSize.width + 22.0, 40);
if ((buttonFrame.origin.x+buttonFrame.size.width) >_subADCView.frame.size.width)
{
x=0;y=_subADCView.frame.size.height;
_subADCView.frame=CGRectMake(_subADCView.frame.origin.x, _subADCView.frame.origin.y, _subADCView.frame.size.width, _subADCView.frame.size.height+frameHeight);
buttonFrame = CGRectMake(x, y, fontSize.width+ 22.0, 40);
}
x = x + fontSize.width + 35.0; y=y+currentFrame.origin.y;
[btn setFrame:buttonFrame];
//I need to set the button image here
[btn setImage:[[UIImage imageNamed:#"edit_category_middle_up.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0] forState:UIControlStateNormal];
[btn setImage:[[UIImage imageNamed:#"edit_category_middle_down.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0] forState:UIControlStateHighlighted];
[btn setTitle:titleString forState: UIControlStateNormal];
[btn setTag:i];
lastButtonPosition=btn.frame.origin.y+btn.frame.size.height;
}
[self.subADCView addSubview:btn];
}
[self readjustSubviews];
}
You only need the background in a single image if you use the following technique.
UIImage *backgroundImage = [[UIImage imageNamed:#"MyImageTitle"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, leftInset, 0, rightInset)];
where leftInset is the width of unstretchable content from the left side of the image and rightInset is the width of unstretchable content from the right side of the image.
This will create an image that only stretches content inside the defined insets. This is the best way to solve this problem.
Alternatively, if you cannot possibly combine your images then you can do it like this.
UIImage *leftImage = [UIImage imageNamed:#"edit_category_left_up"];
UIImage *middleImage = [UIImage imageNamed:#"edit_category_middle_up"];
UIImage *rightImage = [UIImage imageNamed:#"edit_category_right_up"];
UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, leftImage.size.width, btn.frame.size.height)];
[leftImageView setImage:leftImage];
UIImageView *middleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(leftImageView.frame.size.width, 0, btn.frame.size.width - (leftImage.size.width + rightImage.size.width), btn.frame.size.height)];
[middleImageView setImage:middleImage];
UIImageView *rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(middleImageView.frame.origin.x + middleImageView.frame.size.width, 0, rightImage.size.width, btn.frame.size.height)];
[rightImageView setImage:rightImage];
[btn addSubview:leftImageView];
[btn addSubview:middleImageView];
[btn addSubview:rightImageView];
You might need to play around with the layer the subviews are inserted at. To do that you can use one of these methods:
[btn insertSubview:view aboveSubview:otherView];
[btn insertSubview:view atIndex:someIndex];
[btn insertSubview:view belowSubview:otherView];
Try this code to combine three images
-(UIImage*)combineImages
{
UIImage *image1 = [UIImage imageNamed:#"test.png"];
UIImage *image2 = [UIImage imageNamed:#"yyu.png"];
UIImage *image3=[UIImage imageNamed:#"test.png"];
//self.imageView.image=image3;
CGSize size = CGSizeMake(image1.size.width+image2.size.width+image3.size.width, image1.size.height );
UIGraphicsBeginImageContext(size);
[image1 drawInRect:CGRectMake(0,0,image1.size.width, size.height)];
[image2 drawInRect:CGRectMake(image1.size.width,0,image2.size.width, size.height)];
[image3 drawInRect:CGRectMake(image1.size.width+image2.size.width, 0,image3.size.width,size.height)];
UIImage *finalImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return finalImage;
}
Are you writing for iOS7 only?
If so make a single "stretchable" image and import it into the project using an Asset Catalog.
From here you can then specify the properties of the stretchable image (i.e. cap insets etc...) in the catalog.
Then to set the background image correctly you just use...
[button setBackgroundImage:[UIImage imageNamed:#"BackgroundImage"] forState:UIControlStateNormal];
This will take the resizable/stretchable properties from the asset catalog.
Just look into this thread once. May be this is not for what you are looking, but I hope it may be helpful for you or someone else.
Build a UIImage with multiple stretchable images

No resizing, but positioning when setting backgroundImage of UIButton

I want the button to basically overlap a certain part of the original picture and crop the rest instead of squishing the picture into the button. I can't seem to find a UIContentMode to achieve this.
Try this:
You can have a UIImage after some CGRect inside any UIViews. Just make a CGRect with the part of the UIImageView that contains your original UIImage, and execute the code below:
CGRect newImageFrame = CGRectMake(...); //fill this rect according to the crop area of the imageView
UIGraphicsBeginImageContextWithOptions(newImageFrame, YES, 0);
[editingCell.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Now the newImage will hold the image that you will use as background of your button.
Example:
Assuming your UIImageView has the frame (50,50, 100, 200), you can crop a similar result of your image with something like this: newImageFrame = CGRectMake(50, 130, 100, 40).
Please, let me know if worked or not.
please try this code:
CGRect frame = CGRectMake(10, y, 280, 40);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = frame;
button.tag=i;
[button setTitle:(NSString *)#"new button" forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[UIImage imageNamed:#"temp.png"] forState:UIControlStateNormal];
[self.view addSubview:button];
i have checked it out.
hope this will help you.

Set background image of UIBarButtonItem programmatically changes its size

I've been able to have a custom UIBarButtonItem with an embedded uibutton through story board. It's the map button.
see parameters on this screenshot, I had to use background property instead of Image.
But when I tried to customize some uibarbuttons programmatically, then the buttons get smaller. I had the same result with the map button when I was using Image property.
Here the code i'm writing for the back button,
UIImage *backButtonImage = [[UIImage imageNamed:#"Retour.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(21, 21, 21, 21)] ;
backButtonImage = [backButtonImage stretchableImageWithLeftCapWidth:0 topCapHeight:0];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, backButtonImage.size.width, backButtonImage.size.height);
[button setBackgroundImage:backButtonImage forState:UIControlStateNormal];
[button setBackgroundImage:backButtonImage forState:UIControlStateHighlighted];
[button addTarget:self action:#selector(back) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:button] ;
self.navigationItem.leftBarButtonItem = backBarButton;
I tried with or without resizableImageWithCapInsets, stretchableImageWithLeftCapWidth with the same result below (the back button should have the same size as the map button)
I tried also iOS 5 setBackButtonBackgroundImage methods but the button was not customized at all.
If you don't find an answer to your problem, I can suggest you this function :
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
//UIGraphicsBeginImageContext(newSize);
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
It returns an image scaled to the specified size.
So you can resize your image at the desired size and then set it as a background image.
Well the problem was that I had overwritten the Retour#2x.png for retina display with Retour.png -__-'

UIButton with resizable Image

Ok guys,
i know i am doing something wrong, but i cannot figure that out. here is the code that will
put the resizable image for the normal button state.
self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
UIImage *image = [[UIImage imageNamed:#"loginbutton_image"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,10.0,0.0,10.0)];
[self.loginButton setImage:image forState:UIControlStateNormal];
[self addSubview:self.loginButton];
Here is the image
either the image asset is wrong or the code.
the image is of 21 px width.
the cap inset of 10 & 10 on left right leaves 1Px to resize.
does any one spot what i am doing wrong.
thanks all for stopping by
Arun
you should do it this way:
self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
UIImage *image = [[UIImage imageNamed:#"loginbutton_image"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,10.0,0.0,10.0)];
[self.loginButton setBackgroundImage:image forState:UIControlStateNormal];
[self.view addSubview:self.loginButton];
This way you are setting the background image property of the button. The background image is already attached to the button view, so no need to addSubview.
try
self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.loginButton.frame = CGRectMake(0.0, 44.0, 314, 44);
UIImage *image = [[UIImage imageNamed:#"loginbutton_image"] stretchableImageWithLeftCapWidth:10 topCapHeight:10]; //assuming the height is 44
[self.loginButton setImage:image forState:UIControlStateNormal];
[self addSubview:self.loginButton];

Resources