How to fill background image of an UIView - iphone

I have an UIView and I set a background image in this way:
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"sfond-appz.png"]];
My problem is that back-image is not centered inside the view, but it's replayed some times to fill all the view. Is there a way to center image inside uiview and scretch to have screen size?
Note: I can't use UIImageView for background cause I have a scrollview.

You need to process the image beforehand, to make a centered and stretched image.
Try this:
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:#"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];

For Swift use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "ImageName.png")?.draw(in: self.view.bounds)
if let image = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
}else{
UIGraphicsEndImageContext()
debugPrint("Image not available")
}

The colorWithPattern: method is really for generating patterns from images. Thus, the customization you require is most likely not possible, nor is it meant to be.
Indeed you need to use a UIImageView to center and scale an image. The fact that you have a UIScrollView does not prevent this:
Make self.view a generic view, then add both the UIImageView and the UIScrollView as subviews. Make sure all is wired up correctly in Interface Builder, and make the background color of the scroll view transparent.
This is IMHO the simplest and most flexible design for future changes.

Repeat:
UIImage *img = [UIImage imageNamed:#"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];
Stretched
UIImage *img = [UIImage imageNamed:#"bg.png"];
view.layer.contents = img.CGImage;

Correct way to do in Swift 4,
If your frame as screen size is correct then put anywhere otherwise,
important to write this in viewDidLayoutSubviews because we can get actual frame in viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
UIGraphicsBeginImageContext(view.frame.size)
UIImage(named: "myImage")?.draw(in: self.view.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
view.backgroundColor = UIColor.init(patternImage: image!)
}

For Swift 2.1 use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "Cyan.jpg")?.drawInRect(self.view.bounds)
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)

You can use UIGraphicsBeginImageContext method to set the size of image same that of view.
Syntax : void UIGraphicsBeginImageContext(CGSize size);
#define IMAGE(imageName) (UIImage *)[UIImage imageWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:imageName ofType:IMAGE_TYPE_PNG]]
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:#“MyImage.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:IMAGE(#"mainBg")];

For Swift 3.0 use the following code:
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "bg.png")?.drawAsPattern(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)

The marked answer is fine, but it makes the image stretched.
In my case I had a small tile image that I wanted repeat not stretch.
And the following code was the best way for me to solve the black background issue:
UIImage *tileImage = [UIImage imageNamed:#"myTileImage"];
UIColor *color = [UIColor colorWithPatternImage:tileImage];
UIView *backgroundView = [[UIView alloc] initWithFrame:self.view.frame];
[backgroundView setBackgroundColor:color];
//backgroundView.alpha = 0.1; //use this if you want to fade it away.
[self.view addSubview:backgroundView];
[self.view sendSubviewToBack:backgroundView];

Swift 4 Solution :
#IBInspectable var backgroundImage: UIImage? {
didSet {
UIGraphicsBeginImageContext(self.frame.size)
backgroundImage?.draw(in: self.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image{
self.backgroundColor = UIColor(patternImage: image)
}
}
}

Related

UIImage from object c to swift and image size bad

i've a PNG image that i would insert into my navigation title.
In Object C i've
UIImage *image = [UIImage imageNamed:#"logo_up.png"];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:image];
CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
it works very well and my image was in high quality
Then i create a similar APP in swift, using the same image, and write this code
self.navigationItem.titleView = UIImageView(image: UIImage(named: "icons/logo_up.png"))
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.frame.size.width = 320
self.navigationController?.navigationBar.frame.size.height = 44
it print my image but with very poor quality.
I create different image with different size but nothing change. Every image in this APP have poor quality.
I use PNG and JPG extension.
Try to play with the content mode of your UIImageView. You are changing the frame of the UINavigationBar in your Swift example, the image can be reduced in quality by doing this.
let imageView = UIImageView(image: UIImage(named: "icons/logo_up.png"))
imageView.contentMode = .ScaleAspectFit //change contentMode
self.navigationItem.titleView = imageView
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor() self.navigationController?.navigationBar.frame.size.width = 320
self.navigationController?.navigationBar.frame.size.height = 44

UIView drawInRect with UIImage results in blackbackground

I have this following codes:
#implementation MyImageView
#synthesize image; //image is a UIImage
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void) removeFromSuperview
{
self.image = nil;
[super removeFromSuperview];
}
- (void)drawRect:(CGRect)rect
{
// Drawing code
if (self.image)
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
//the below 2 lines is to prove that the alpha channel of my UIImage is indeed drawn
//CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
//CGContextFillRect(context, rect);
CGContextDrawImage(context, self.bounds, self.image.CGImage);
}
}
#end
When I ran the code, I realized that the background of my view is black. To test if it was a problem with my UIImage, I used the 2 lines commented after CGContextClearRect(context, rect). Indeed a white background was drawn. Is there anyway for me to remove the black background? When I init MyImageView, i have already set backgroundColor to [UIColor clearColor].
Any advice is much appreciated.
Thanks
Setting the background color to [UIColor clearColor] should work. Also set self.opaque = NO to enable transparency.
You should also check that the correct initializer is being called. For example if the view is part of a XIB file, you need to implement initWithCoder: as well as initWithFrame: etc.
I had the same issue - this worked for me (Swift example)
var backgroundImage = UIImage() //background image - size = 100x100
var frontImage = UIImage() //smaller image to be drawn in the middle
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), false, 0.0) //false here indicates transparent
var context = UIGraphicsGetCurrentContext()!
UIGraphicsPushContext(context)
backgroundImage.drawInRect(CGRectMake(0, 0, 100, 100))
frontImage.drawInRect(CGRectMake((100 - frontImage.size.width) / 2, (diameter - frontImage.size.height) / 2, frontImage.size.width, frontImage.size.height))
UIGraphicsPopContext()
var outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
Your CGContext will draw upside down
anyhow, so just go the easy route and use
[self.image drawInRect:CGRectMake(rect)];
Instead.

How to stretch Image to fill the Label Width set in Background in UILabel?

I have simple View based application. I had taken only UILabel on it.
Following is my code in viewDidLoad:
lblBack.textColor = [UIColor blueColor];
UIImage *img = [UIImage imageNamed:#"cn3.png"];
lblBack.backgroundColor = [UIColor colorWithPatternImage:img];
lblBack.text = #"Hello World!!!...";
// UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
//
// CGRect rect = CGRectMake(0, 0, lblBack.frame.size.width, lblBack.frame.size.height);
// [imgView setFrame:rect];
// NSLog(#"Rect : %#",NSStringFromCGRect(rect));
// [img drawInRect:rect];
// imgView.contentMode = UIViewContentModeScaleAspectFill;
// imgView.contentMode = UIViewContentModeScaleAspectFit;
// imgView.contentMode = UIViewContentModeScaleToFill;
// [lblBack addSubview:imgView];
Comments shows some of the things that i have tried. I am getting following output:
In this one image is repeated 3 times. But I want that image should be stretched to fill the Label width.
I have referred some of the previous links that shows me to add Image in background and use clearColor for UILabel. Also seen example of Adding custom view in Background. But all this I dont want to use unless I dont have other solutions...
I just want to perform all things on UILabel only.... no other control except UIImage or UIImageView i want to use..
Dhiren try this code :
UIImage *img = [UIImage imageNamed:#"cab.png"];
CGSize imgSize = testLabel.frame.size;
UIGraphicsBeginImageContext( imgSize );
[img drawInRect:CGRectMake(0,0,imgSize.width,imgSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
testLabel.backgroundColor = [UIColor colorWithPatternImage:newImage];
I have tested this code.
Porting over Maulik's answer to Swift 2.2, you get the following code:
var img: UIImage = UIImage(named: "cabImage")!
var imgSize: CGSize = testLabel.frame.size
UIGraphicsBeginImageContext(imgSize)
img.drawInRect(CGRectMake(0, 0, imgSize.width, imgSize.height))
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
testLabel.backgroundColor = UIColor(patternImage: newImage)
Personally tested to be working!

set background image for entire iPhone / iPad app

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];
}

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];