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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With