UIView background image gets squashed
In my iPhone app I have a UIView with a tiled background image created via view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"I开发者_如何学JAVAndexCard.png"]];
On my iOS3.1 device, when the view gets resized, the background image gets squashed - i.e. it tiles the same number of times but the height of each tile is reduced. Instead I would like each tile to stay the same size but the number of repeats to adjust according to the new view size. If I clear the background and then reset it the problem gets fixed, but that seems like a particular innefficient solution to the problem. On the iOS4.3 simulator it works correctly.
Here's the original image - 12 lines:
Here's what I'm seeing when I resize the view - it still has 12 lines:
Whereas here's what I'd really like to see - the background would be cropped to 5 lines:
Any ideas?
The view's backgroundColor
property is assigning a color (or pattern) to the CALayer
that is the basis for drawing the view. You can change the CALayer's properties by addressing the layer
property of the view.
Looking through the CALayer Class Reference I see that there's a property called contentsGravity
that:
Determines how the receiver's contents are positioned within its bounds.
It indicates that:
The possible values for
contentsGravity
are shown in “Contents Gravity Values”. The default value iskCAGravityResize
.
That explains why your image is being squished like that: by default it's resizing the image. Taking a look at the other Contents Gravity Values there are a couple of options that are likely best for you:
kCAGravityTop
: The content is horizontally centered at the top-edge of the bounds rectangle.
kCAGravityCenter
: The content is horizontally and vertically centered in the bounds rectangle.'kCAGravityBottom': The content is horizontally centered at the bottom-edge of the bounds rectangle.
I'd guess that kCAGravityTop
is probably what you're looking for, so you'd set your view's layer's contentsGravity
like this:
view.layer.contentsGravity = kCAGravityTop;
I found a much simpler solution:
view.contentMode = UIViewContentModeRedraw;
// instead of the default UIViewContentModeScaleToFill
精彩评论