Set background - centered and not stretched

40 views Asked by At

The programm sets the background as an image through:

 [backgroundViewProxy setBackgroundColor:[UIColor colorWithPatternImage:[theme backgroundImage]]];

The drawRect of the correspoinding UIView is:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGSize phase = self.backgroundShift; //set this property to affect the positioning of the background image
    CGContextSetPatternPhase(context, phase);

    CGColorRef color = self.backgroundColor.CGColor;
    CGContextSetFillColorWithColor(context, color);
    CGContextFillRect(context, self.bounds);
    CGContextRestoreGState(context);
}

I did not wrote the code on my own. I have to modify it. I do understand what is going on here, but i cannot find a way to solve this problem:

I want the image to be centered on the screen (with and height) and it should not be streched or repeated.

At the moment, the image is repeated to fill the screen. I have searched around the internet, but did not find a clear solution for centering(or positioning) the image in a similar context like this.

I would be glad if someone could help.

1

There are 1 answers

0
Dare On

From apple's docs:

+ (UIColor *)colorWithPatternImage:(UIImage *)image

You can use pattern colors to set the fill or stroke color just as you would a solid color. During drawing, the image in the pattern color is tiled as necessary to cover the given area.

An alternative could be setting view.layer.contents to you image by casting it as type (id)