set background image for entire iPhone / iPad app - iphone

I have a single image I want as the background for my app no matter what viewcontroller they are on - how do you accomplish this?

Here's how you set a background to an image:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Background.png"]];
Edit: To write up what Felixyz said (and thanks to Manni), do this in your delegate:
window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Background.png"]];
And in each view you want to have the image, do this:
self.view.backgroundColor = [UIColor clearColor];

Depends on what sort of interface you have. Tabbed? Navigation based? But the general answer is: add a UIImageView to your UIWindow before/below your main view. Then make every view handled by your main view controller have a transparent background. Hard to give more specific advice without knowing if you use IB or not, or what your view hierarchy looks like.

In my app, I set a default background color. Maybe you can do this with you background image:
1.: Set the background color of your UIWindow in your AppDelegate:
window.backgroundColor = [UIColor myBackgroundGray]; // own Category
2.: And now, make all other views transparent:
self.view.backgroundColor = [UIColor clearColor]; // = transparent

In your AppDelegate in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Add this line :
[self.window setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]]];
After you just have to set your views backgrounds to [UIColor clearColor];

I am not sure of the performance implications, but I needed to accomplish something similar, and ended up using a UIImageView which works well (in C#, but works the same in obj-c):
//Add the view controller first, to ensure proper order of views later.
Window.RootViewController = new UIViewController();
//create backdrop image view
var imageView = new UIImageView(Window.Bounds);
imageView.Image = UIImage.FromBundle("backdrop.jpg");
//insert into window.
Window.InsertSubview(imageView, 0);
This doesn't handle orientation changes, but in my case, allowed me to add motion effects to the backdrop (such as parallax).

Your background is a property of any View-inheriting object. Labels, Buttons, Controllers, and the app window, for example, all have backgrounds. If you want it to be completely a bg for the entire app you must climb the path in your controllers to find the very "top" (bottom-viewed) view, and set its background to be the image you desire.

just call this assignbackground in viewDidLoad
override func viewDidLoad() {
assignbackground()
}
func assignbackground(){
let background = UIImage(named: "background")
var imageview : UIImageView!
imageview = UIImageView(frame: view.bounds)
imageview.contentMode = UIViewContentMode.ScaleAspectFill
imageview.clipsToBounds = true
imageview.image = background
imageview.center = view.center
view.addSubview(imageview)
self.view.sendSubviewToBack(imageview)
}

I usually use this function to avoid overlaps with navigation bar on iphone.
-(void)setImageBackground:(NSString*)imageName{
UINavigationController* navigationController = [self navigationController];
float height = navigationController.toolbar.frame.size.height;
CGSize size = self.view.frame.size;
size.height = size.height;
UIGraphicsBeginImageContext(size);
CGRect bounds = self.view.bounds;
bounds.origin.y = bounds.origin.y + height;
bounds.size.height = bounds.size.height-height;
[[UIImage imageNamed:imageName] drawInRect:bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
}

Related

UIView subclass can't change from black background

I've created a subview of UIView to make some drawings - the drawings work fine in the drawRect method of my subclass, however, I cannot change the background color of the view. A little googling tells me I haven't set the frame for the view, but I'm not entirely sure how to do this. I tried two things:
I create the view in Storyboard and add it to my view controller, then declare it as a property in the header file and link them up. I synthesize the property at the top of the implementation file and in the viewDidLoad method, I add:
[myView setBackgroundColor: [UIColor whiteColor]];
The view's background is still black.
I also tried:
ViewSubclass *v = [[ViewSubclass alloc] initWithFrame: self.view.frame];
v.backgroundColor = [UIColor whiteColor];
myView = v;
To no avail.
What am I doing wrong?
UPDATE: This is the code I use to draw in the view, in case there's something going on there!
- (void)drawRect:(CGRect)rect {
CGFloat height = self.bounds.size.height;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
CGContextSetFillColorWithColor(context, [UIColor grayColor].CGColor);
CGFloat barWidth = 30;
int count = 0;
for (NSNumber *num in samples) {
CGFloat x = count * (barWidth + 10);
CGRect barRect = CGRectMake(x, height - ([num floatValue] * height), barWidth, [num floatValue] * height);
CGContextAddRect(context, barRect);
count++;
}
CGContextFillPath(context);
}
It just creates a set of bars in the screen, of different heights.
CGContextClearRect From the docs:
If the provided context is a window or bitmap context, Quartz
effectively clears the rectangle. For other context types, Quartz
fills the rectangle in a device-dependent manner. However, you should
not use this function in contexts other than window or bitmap
contexts.
It might be that this clearing clears your entire view with no regard to the background color you set
I can t add comments due my low lvl, but the question springs to mind, have you added to your UIView to viewcontroller?
like
[self.view addSubview:v];
EDIT:
I'm sorry I had understood that the second option was added to the view that pragmatically.
Are you adding the view in the header file? If so you might need to be sure the frame's coordinates are visible and that the view is on top, also make the new view slightly smaller to see if it is actually being created:
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
[self.view addSubview: myView];
[self.view bringSubviewToFront:myView];
You can also change the main view background color to see if the new view is actually being created. For example:
[self.view setBackgroundColor:[UIColor grayColor]];
If the color is changing for your main view then the problem is that your new view is not being or brought to the front. Let us know how it goes!
At the point where do
[myView setBackgroundColor: [UIColor whiteColor]];
check to see if myView is not nil in the debugger

UIImage in a circle

Can somebody help me here?. New as iPhone Developer. I am trying to display a .png picture in a circle instead of a rectangle which is the standard for iPhone
Well, all png files are 'rectangles' but if you want to have the apperence of a circle or other non rectangle object on the screen you can do so by using transparacy. To make sure the transparent pixels in the image are also transparent on the iPhone, you can set the background color of the UIImageView to clear. This can be done in Interface Builder by dragging the opacity slider in the background color picker all the way down,
or in code as follows:
UIImage *image = [UIImage imageNamed:#"yourRoundImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.backgroundColor = [UIColor clearColor];
[self.view addSubview: imageView];
If you simply want to add rounder corners, to make a circle, you can also use the cornerRadius Property like this if you have added the QuartzCore framework to your project:
#import <QuartzCore/QuartzCore.h>
UIImage *image = [UIImage imageNamed:#"yourRoundImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.layer.cornerRadius = image.size.width / 2;
imageView.layer.masksToBounds = YES;
[self.view addSubview: imageView];
try this code
yourImageView.layer.cornerRadius = yourImageView.frame.size.height /2;
yourImageView.layer.masksToBounds = YES;
yourImageView.layer.borderWidth = 0;
this show image like ios 7 circle image thanks
My contribution with a swift extension used to set an UIImageView as circle
extension UIImageView{
func asCircle(){
self.layer.cornerRadius = self.frame.width / 2;
self.layer.masksToBounds = true
}
}
Just call MyImageView.asCircle()
Use a UIImageView and set the cornerRadius to be half height and width. view.layer.cornerRadius = cornerRadius;
UIImage rounded corners
Try this to get rounded corners of the image View and also to colour the corners:
self.imgView.layer.cornerRadius =self.imgView.frame.size.height/2;
self.imgView.layer.masksToBounds = YES;
self.imgView.layer.borderColor = [UIColor colorWithRed:148/255. green:79/255. blue:216/255. alpha:1.0].CGColor;
self.imgView.layer.borderWidth=2;
Condition*: The height and the width of the imageView must be same to get rounded corners.
Changing the cornerRadius of the image view works well if you have only a couple of images in your view. However if the image view is in a tableview performance will be affected.
Some of the other options:
Make the image assets circle on the server or manually if they are bundled into the app, with transparent parts for the outer region of the circle.
If the background of the image view doesn't change, create an overlay image that has the inner circle part transparent, and the rest to be the same as the background. Also set the backgroundColor of the image view to clearColor.
When receiving the images, edit them in code to be a circle, in a background thread.
Swift 4: This should display your .png in a circle.
Drag (ctrl + click) an IBOutlet of an image toward your code.
cornerRadius
The radius to use when drawing rounded corners for the layer’s background. Animatable. https://developer.apple.com/documentation/quartzcore/calayer/1410818-cornerradius
clipsToBounds property
A Boolean value that determines whether subviews are confined to the bounds of the view. https://developer.apple.com/documentation/uikit/uiview/1622415-clipstobounds
2.Inside viewDidLoad(), Use the instance property layer.cornerRadius and clipsToBounds.
profileImage.layer.cornerRadius = 50
profileImage.clipsToBounds = true
I'll add a slightly more universal extension to UIImageView that will work with non-square images.
To be noted that it will work slower than the cornerRadius method.
extension UIImageView {
#IBInspectable public var asEllipse:Bool {
get {
if let mask = self.layer.mask {
return mask.name == kMaskLayerName
}
return false;
}
set {
if (newValue) {
let ellipseMask = CAShapeLayer()
ellipseMask.name = kMaskLayerName
ellipseMask.path = CGPathCreateWithEllipseInRect(self.bounds, nil)
ellipseMask.strokeColor = UIColor.clearColor().CGColor
ellipseMask.fillColor = UIColor.whiteColor().CGColor
self.layer.mask = ellipseMask
} else if self.asEllipse {
self.layer.mask = nil
}
}
}
}
private let kMaskLayerName="EllipseMaskLayer"
On Objective-C it looks like:
UIImage* pIconImage = [UIImage imageNamed:#"ImageName"];
UIImageView* pIconView = [[UIImageView alloc] initWithImage:pIconImage];
[pIconView.layer setCornerRadius:pIconImage.size.width / 2];
[pIconView.layer setMasksToBounds:YES];

How can I get a full-sized UINavigationBar titleView

I am trying to add a custom control as the titleView in a UINavigationBar. When I do so, despite setting the frame and the properties that would normally assume full width, I get this:
The bright blue can be ignored as it is where I am hiding my custom control. The issue is the narrow strips of navbar at the ends of the bar. How can I get rid of these so my customview will stretch 100%?
CGRect frame = CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.width, kDefaultBarHeight);
UANavBarControlView *control = [[[UANavBarControlView alloc] initWithFrame:frame] autorelease];
control.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.navigationItem.titleView = control;
PS - I know I can add the view by itself instead of being attached to a navigation bar and it would be very easy to position it myself. I have my reasons for needing it to be "on" the navigation bar, and those reasons are here
Just ran into the same problem and after a bit of thinking solved it. titleView's frame gets set by the navigationBar every time it appears.
All you have to do is subclass UIView and override setFrame.
Like this:
- (void)setFrame:(CGRect)frame {
[super setFrame:CGRectMake(0.0, 0.0, 320.0, 50.0)];
}
Now set your sneaky new UIView as the navigationItem.titleView and enjoy its newfound resistance to resizing by the superview.
You don't have to set super's frame every time your frame gets set. You can just set it once and be done. If you want to support orientation changes you could probably hack that together too.
Setting the titleView of your view's navigationItem will never do the trick. Instead, you can add a subView to the navigation controller's navigationBar :
UIView* ctrl = [[UIView alloc] initWithFrame:navController.navigationBar.bounds];
ctrl.backgroundColor = [UIColor yellowColor];
ctrl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[navController.navigationBar addSubview:ctrl];
The following code worded on iOS8/iOS9/iOS10/iOS11.
Code in swift 3
class TitleView: UIView {
override var frame: CGRect {
get {
return super.frame
}
set {
super.frame = newValue.insetBy(dx: -newValue.minX, dy: 0)
}
}
override func didMoveToSuperview() {
if let superview = superview {
frame = superview.bounds
translatesAutoresizingMaskIntoConstraints = true
autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
override func updateConstraints() {
super.updateConstraints()
/// remove autolayout warning in iOS11
superview?.constraints.forEach { constraint in
if fabs(constraint.constant) == 8 {
constraint.isActive = false
}
}
}
}
Swift version of ksm's answer
let leftOffset: CGFloat = 60
let rightOffset: CGFloat = 60
#objc override var frame: CGRect {
didSet {
let width: CGFloat = UIScreen.main.bounds.width - leftOffset - rightOffset
let height: CGFloat = 44
super.frame = CGRect(
x: leftOffset,
y: 20,
width: width,
height: height
)
}
}
thanks #VdesmedT for the answers , I have been using this answer to achieve a full screen size titleView in navigationbar .
But, I have just upgraded to iOS11 recently and I found that this solution did not work. And so I figured it out by another way(may seem weird). The core of the idea is not to change the titleView's size, but to change the subViews of the bar to achive the fullscreen bar affects
make a barView (make sure the barView width is screenSize - 12*2, 12
is the system padding set to to titleView, you can use manual layout
or autolayout's constraint to achive this). and then set it as
navigation bar's titleView
add your components into this barView. you can align the components
from -12 to the barView's width + 12
overload your barView's pointInside , to make it respondable even
when the click happed outside the barView.
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
BOOL ret = [super pointInside:point withEvent:event];
if (ret == NO)
{
CGRect expandRect = UIEdgeInsetsInsetRect(self.bounds, UIEdgeInsetsMake(0, -12, 0, -12));
ret = CGRectContainsPoint(expandRect, point);
}
return ret;
}
CGRect frame = CGRectMake(0, 0, 320, 44);
UILabel *titlelabel = [[UILabel alloc]initWithFrame:frame];
titlelabel.textAlignment = UITextAlignmentCenter;
titlelabel.backgroundColor = [UIColor clearColor];
titlelabel.textColor = [UIColor whiteColor];
titlelabel.font = [UIFont systemFontOfSize:20];
titlelabel.text =#"Available Reports";
self.navigationItem.titleView = titlelabel;
if you want to set image then take uiimage view instead on uilable you can create any view of fully navigation bar just tell me how ur navigation look like i will send you code for that if you want i can put 6 button on navigation also

UILabel background color

I am trying to change the UILabel background color with this code
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
m_ShopName.text = m_CurrShop.m_Name;
m_ShopAddress.layer.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0].CGColor;
}
but nothing is happening.
This will help you
UILable *lbl = [[UILabel alloc]initWithFrame:CGRectMake(10,20,50,200)];
lbl.backgroundColor = [UIColor redColor];
Can you do this:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
m_ShopName.text = m_CurrShop.m_Name;
m_ShopAddress.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
}
I always did the following
m_ShopAddress.backgroundColor = [UIColor red];
When I wanted to change the alpha...
m_ShopAddress.alpha = 0.0f;
An alpha value of 0 means, it's fully transparent. That's probably why nothings happens (whatever you mean by that).
And I wouldn't access the background color of the layer, but of the UILabel directly.
If you are using a storyboard, check to see if you have a color for the view background in the storyboard. The view background color was overriding the layer color for me. I changed the background color for the view in the storyboard to default and this fixed it for me.
So I had the code:
func select() -> Void {
imageViewBackgroundView.layer.backgroundColor = UIColor.black.cgColor
cellImageView.layer.backgroundColor = UIColor.black.cgColor
cellLabel.layer.backgroundColor = UIColor.black.cgColor
cellLabel.textColor = UIColor.white
}
The cellLabel was the view background that was not changing. I had at one time set a background color for the view in the Storyboard. Once I changed the view background for the cellLabel to default the layer color took effect.
View Background

using image or tint color on uinavigationbar in iphone?

how do i show a background image on a navigation bar or give tint color to the navigation bar in a native iphone application??
For iOS5 use the following lines of code:
UINavigationBar *navBar = [[self navigationController] navigationBar];
UIImage *backgroundImage = [UIImage imageNamed:#"nav-bar-background-normal"];
[navBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];
For backward compatibility do a check to see if the navigation bar responds to setBackgroundImage:forBarMetrics:
More information on:
http://sebastiancelis.com/2009/12/21/adding-background-image-uinavigationbar/
This's how I did on iOS4:
#import <QuartzCore/QuartzCore.h> // For .layer
self.navigationController.navigationBar.layer.contents = (id)[UIImage imageNamed:#"navigationBarBackgroundImage"].CGImage;
self.navigationController.navigationBar.tintColor = [UIColor orangeColor];
No need to switch subviews between z-orders (-exchangeSubviewAtIndex:withSubviewAtIndex:), both background image and tintColor set in one line of code, and works with #2x image too.
Was looking for this a week ago. Found this over here discussions. apple. com/thread.jspa?threadID=1649012&tstart=0 (sorry won't let me post a real link).
-(void)setBackgroundImage:(UIImage*)image withTag:(NSInteger)bgTag{
if(image == NULL){ //might be called with NULL argument
return;
}
UIImageView *aTabBarBackground = [[UIImageView alloc]initWithImage:image];
aTabBarBackground.frame = CGRectMake(0,0,self.frame.size.width,self.frame.size.height);
aTabBarBackground.tag = bgTag;
[self addSubview:aTabBarBackground];
[self sendSubviewToBack:aTabBarBackground];
[aTabBarBackground release];
}
/* input: The tag you chose to identify the view */
-(void)resetBackground:(NSInteger)bgTag {
[self sendSubviewToBack:[self viewWithTag:bgTag]];
}
I made this as a category to UINavigationBar. To set it a background image for a UINavigationBar inside a UINavigationBarController, I did this:
[navigationControllerForChannels.navigationBar setBackgroundImage:[UIImage imageNamed:#"top_bar.png"] withTag:48151623];
I've had some buginess when updating the tab bar, so you'll want to call
[self.navigationController.navigationBar resetBackground:48151623];
After any modifications to the bar.
You can override UINavigationBar drawRect. The code can be placed to appDelegate.m
I've tested it and it's working on 3x and 4x iOS.
#implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
UIColor *color = [UIColor blackColor]; //tint color
UIImage *img = [UIImage imageNamed: #"navBarBg.png"]; // your image
[img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
self.tintColor = color;
}#end
For the iOS5 and iOS6 I've used this solutions and it worked perfectly, Making a Universal UINavigationBar Background Image.
iPhone Retina Portrait 640px x 88px / iPhone Non-Retina Portrait 320px x 44px
Inside AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
Place this code
// Set the status bar to black color.
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:NO];
// Change #"menubar.png" to the file name of your image.
UIImage *navBar = [UIImage imageNamed:#"menubar.png"];
[[UINavigationBar appearance] setBackgroundImage:navBar forBarMetrics:UIBarMetricsDefault];
Don't forget to change the image name (menubar.png)
Check out this link for the full answer http://www.lwxted.com/blog/2012/add-custom-background-image-uinavigationbar-ios-5/
a background image is going to take a bit more work (you might want to try setting a titleView that's the same size as the bar itself; I haven't tried this myself) or adding a view behind existing subviews. Tint color is easy: navBar.tintColor = [UIColor orangeColor];
If you use the CGImage solution, you may have a problem with image size:
CGRect layer=self.navigationController.navigationBar.frame;
layer.size.height=57.0;
layer.origin.y=0;
self.navigationController.navigationBar.frame=layer;
CGImageRef imageRef = [UIImage imageNamed:#"myImg.png"].CGImage;
self.navigationController.navigationBar.layer.contents = (id)imageRef;
It seems to me that the image is streched down, since the layer seems to have a height of 44.0 pixel, but a background image for the UINavigationBar should be at least 57.0.
If you try to move the layer's frame, all the buttons will move within it.