Using an LSR image on a UIButton - objective-c

I am creating a tvOS app and I want to use parallax images on a couple of buttons. From the docs:
To incorporate parallax images in your app:
Create a UIImage object.
You load the image differently depending on whether the image is included in your app bundle or whether you have downloaded the
image.
Bundle—Load images using imageNamed:.
Downloaded file—Load images using imageWithContentsOfFile:.
Create a new UIImageView object using the loaded images.
If the UIImageView is part of another view, set adjustsImageWhenAncestorFocused to YES on the UIImageView.
I know it says UIImageView there, but I was hoping to make the same effect happen on a UIButton, like the home screen app icons.
I've created the artwork, made a stack in the asset catalog, and loaded the image with imageNamed:, but the UIButton does not behave like a parallax image. It does not sway around like the home-screen icons do. It just looks like a flat image.
Is there something else I have to enable in order for the UIButton to behave like the home screen app icons?
UIButton* quitGame = [[UIButton alloc] initWithFrame:rectWithNewX(playAgain.frame, 985)];
[quitGame setImage:[UIImage imageNamed:#"quit.lsr"] forState:UIControlStateNormal];
[quitGame setAdjustsImageWhenHighlighted:YES];
fadeIn(quitGame, self.view, 0.5);

As of right now, this is not possible with just UIButtons, however, I did find a workaround.
Instead, create a UIImageView that will fill the size of the UIButton and make it a subview of the UIButton. Then call the adjustsImageWhenAncestorFocused: and set it to true. Voila!
UIButton* playAgain = [[UIButton alloc] initWithFrame:CGRectMake(centerX(650, self.view), sh() - 250, 300, 180)];
[playAgain setAdjustsImageWhenHighlighted:YES];
[playAgain addTarget:self action:#selector(playAgain) forControlEvents:UIControlEventPrimaryActionTriggered];
fadeIn(playAgain, self.view, 0.5);
UIImageView* playAgainIGV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 180)];
[playAgainIGV setImage:[UIImage imageNamed:#"playagain.lsr"]];
[playAgainIGV setAdjustsImageWhenAncestorFocused:YES];
[playAgain addSubview:playAgainIGV];

I've had issues when setting files or precompiled LSRs.
Creating the LSR in XCode Asset Catalogue through Asset Catalogue -> New Apple TV Image Stack and dragging in the PNGs, then setting the image either through Interface Builder or through this works:
-(void) setLsr:(UIButton *)button lsrNamed:(NSString *)lsr {
[button setAdjustsImageWhenHighlighted:YES];
UIImageView *biv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, button.frame.size.width, button.frame.size.height)];
[biv setImage:[UIImage imageNamed:lsr]];
[biv setAdjustsImageWhenAncestorFocused:YES];
[button addSubview:biv];
}

Regarding the answer of david I made a simple Swift method to create a parallax effect button:
func createParallaxButton(button: UIButton, imageNamed: String) {
button.adjustsImageWhenHighlighted = true
let buttonBg = UIImageView(image: UIImage(named: imageNamed))
buttonBg.adjustsImageWhenAncestorFocused = true
buttonBg.frame = button.bounds
button.addSubview(buttonBg)
}
createParallaxButton(myButton, imageNamed: "myButtonimage.lsr")

Related

UIImageView places on UIButton

I want to place an UIImageView on UIButton programmatically (with constraints). The UIButton is implemented from Storyboard. I don´t find example from the net. I tried this code:
//Test Image button
UIImageView* iqImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"iq1"]];
iqImageView.frame = CGRectMake(0, 0, self.iqCategoryButton.frame.size.width, self.iqCategoryButton.frame.size.height);
iqImageView.contentMode = UIViewContentModeRedraw;
[self.iqCategoryButton addSubview:iqImageView];
The problem is at this moment, the frame´s size of the button is not equal as it will be seen on the screen (due to constraints).

Setting UIButton image results in blue button in iOS 7

On iOS 6 SDK I wrote the following lines of code to display an image inside a button:
NSURL *thumbURL2 = [NSURL URLWithString:#"http://example.com/thumbs/2.jpg"];
NSData *thumbData2 = [NSData dataWithContentsOfURL:thumbURL2];
UIImage *thumb2 = [UIImage imageWithData:thumbData2];
[btn2 setImage:thumb2 forState:UIControlStateNormal];
[self.view addSubview:btn2];
But now with Xcode 5 and iOS 7 this doesn't work. The button doesn't contain the image. The button is filled with blue color.
In iOS7 there is new button type called UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0), // standard system button
Check your .xib file and change button type to Custom
To do this programmatically, add this line to the viewDidLoad:
[UIButton buttonWithType:UIButtonTypeSystem];
It seems iOS 7 is using the image provided just as an Alpha mask for displaying the button's tint color.
Changing the button type to UIButtonTypeCustom did the trick for me (thanks user716216!).
Setting the image as background doesn't always work if you already have a background image, as was my case.
Swift 3, 4, 5 :
let image = UIImage(named: "my-image")
myButton.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)
There's a good chance that the image is there and you just can't see it. Try changing the button's type to UIButtonTypeCustom. If that doesn't work, set the button's background color to [UIColor clearColor];
For swift:
let aButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
The issue is the TintColor. By default, iOS throws a blue tint color over every button. You can get around it through 3 ways.
Change the tint color. [button setTintColor:[UIColor blackColor]];
This may color your image in ways you don't want it to.
As most other suggested, set the background image. [button setBackgroundImage:[UIImage...]];
Add an UIImageView to your button.
UIImageView * img = [[UIImageView alloc] initWithImage:[UIImage...]];
[button addSubView:img];
I had the same issue.
On my storyboard I had a button without any image.
I would then assign the image in the code.
IOS 7 came and I got a lot of blue images.
The resolution was simple yet confusing. If I assign any image on the storyboard and then change the image at run time it works fine.
You always must specify a starting image on the storyboard even if you are not going to use it.
This worked for me
[myButton1 setBackgroundImage:[UIImage imageNamed:#"phones.png"] forState:UIControlStateNormal];
Note:Remove front image before doing this.
Old thread, but I wanted to chime in because I just had the same problem. The issue was just that you are calling setImage when you should call setBackgroundImage.
In iOS 13 -- just set the Tint property to White, while keeping the type of the UIButton as Custom
None of the given solutions were working for me. If you do not set an initial image in Storyboard, you can still change the image of the button by using setBackgroundImage.
For your example, only a minor change is needed.
NSURL *thumbURL2 = [NSURL URLWithString:#"http://example.com/thumbs/2.jpg"];
NSData *thumbData2 = [NSData dataWithContentsOfURL:thumbURL2];
UIImage *thumb2 = [UIImage imageWithData:thumbData2];
[btn2 setBackgroundImage:thumb2 forState:UIControlStateNormal];
[self.view addSubview:btn2];
This Problem is called blue color problem of the button in xcode.
When we make button by code the button shows the blue tint color by default.This can be solved byt assigning tint color to black or white accordingly to your cell's color.
The code is :
UIImage *closebtnimg = [UIImage imageNamed:#"icon_uncheck.png"];
UIImage *closebtnimg1 = [UIImage imageNamed:#"icon_checked.png"];
Custombutton *button = [Custombutton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(52, 66, 25, 24)];
[button setBackgroundImage:closebtnimg forState:UIControlStateNormal];
[button setBackgroundImage:closebtnimg1 forState:UIControlStateSelected];
[button setTintColor:[UIColor whiteColor]];
[cell.contentView addSubview:button];
[button addTarget:self action:#selector(changeImage:) forControlEvents:UIControlEventTouchUpInside];
Using Xcode 9.2 none of the above solutions worked for what I was looking for.
I was looking for a solution that will let me set .normal and .selected UIControlState images inside the storyboard for their original rendering mode, but, inside the Swift file, no string literals should exist regarding the image names.
Basically, inside your code you will get the image you set inside your storyboard for .normal state and re-render it as .alwaysOriginal (Same for .selected state), then, you will set that image (which is now rendered as original and won't be affected by the tint) for the relevant state (.normal and .selected) of your UIButton.
Here it is:
// Get your .normal image (you set via your storyboard) and render it as original
let unselectedImage = yourButton.image(for: .normal)?.withRenderingMode(.alwaysOriginal)
// Set your normal image but this time rendered as original
yourButton.setImage(unselectedImage, for: .normal)
// Same for selected state
let selectedImage = yourButton.image(for: .selected)?.withRenderingMode(.alwaysOriginal)
yourButton.setImage(selectedImage, for: .selected)
This way you can set your button image states and if the image name will change, it won't affect your code.
making the tint color as clearcolor for all the four states(Default,Highlighted,selected,disabled) worked for me.
In Swift 4, initialize your UIButton and assign uyour image Data as follows:
let myButton = UIButton(type: .cutsom)
myButton.setImage(UIImage(data:myImageData), for: .normal)

Image aspect ratio change after inserting it into imageview

So I'm trying to load an image from camera into image view. I've got it done, but images aspect ratio changes.
I tried setting content mode for imageview but no effect.
Here is how i do it:
UIImage *picture=[UIImage imageWithData:slika];
imageview = UIViewContentModeScaleAspectFit;
[imageview setImage:picture forState:UIControlStateNormal];
Any ideas?
Is image view your own view? Or it's, for example, cell's default imageView?
And you should write so:
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.image = [UIImage imageNamed:picture];
or
[imageView setImage:picture];
There is no method [imageview setImage:picture forState:UIControlStateNormal]; for UIImageView, it only available for UIButton (and may be for some other UIControls, but UIImageView not subclass of UIControl - it direct subclass of UIView) . But button does not scale images preserving aspect ratio.

iOS: Background image in UIImagePickerController is inconsistent with the rest of the app

I'm using the following code to set the navbar's background:
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:#"tile.png"] forBarMetrics:UIBarMetricsDefault];
This results in a nice tiled background such as you see here:
However, when I open up a UIImagePickerController, the background is warped somehow and we end up with something like this:
Anyone have suggestions on how to fix it?
Stretching instead of tiling: to Stop That
Create a class of type UINavigationBar
Create your custom UINavigationBar subclass.
Comment initwithFrameMethod
Add method DrawRect:
(void)drawRect:(CGRect)rect
{
UIImage *image = [UIImage imageNamed:#"bluebackground.jpeg"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
4.in AppDelegate.m, AppliocationdidFinishLaunching
Write
[self.navigationbar setValue:[[customBar alloc]init] forKeyPath:#"navigationBar"];
Adding Image By this way will not stretch the image
Refer this Link:
http://www.iosdevnotes.com/2011/09/custom-uinavigationbars-techniques/
http://designm.ag/tutorials/designing-a-custom-iphone-app-navigation-bar/
Hope this will help you.

BarButtonItem resizing for unknown reason

I have a button that is initialized like that>
self.button = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:#selector(doAction)];
Later, I am attaching a custom background to it, like that>
[self.button setBackgroundImage:[UIImage imageNamed:#"customNavBar_button_right_enabled"]
forState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
and puting it onto navbar.
[self.navigationItem setRightBarButtonItem:self.button
animated:NO];
This image has fixed size. I want that button to have fully custom background image with no "intelligent" resizing with UIEdgeInsets.I don't want any resizing. But for some reason, it behaves like its insets would be active and it is resized to have bigger width, with roughly the middle half of picture considerably stretched to provide for the wider button.
Why is this happening? How can I prevent this to happen?
The easiest way to achieve a bar button item with a custom image is by:
Drag a UIButton onto the storyboard.
Set the button Type to Custom and set your image for that button.
Drag the button onto your Toolbar.
The storyboard automatically creates a UIBarButtonItem and adds your UIButton as a subview. Or if you do NOT want to use storyboards you could implement the following:
// Initialize the UIButton
UIImage *buttonImage = [UIImage imageNamed:#"buttonImage.png"];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setImage:buttonImage forState:UIControlStateNormal];
aButton.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
// Initialize the UIBarButtonItem
UIBarButtonItem aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];
// Set the Target and Action for aButton
[aButton addTarget:self action:#selector(aButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
Hope it helps!
EDIT: Do not forget to add the aBarButtonItem to the UIToolbar.