2012-01-31 35 views
1

我看到其他帖子,但仍無法讓我的背景圖像正確縮放。我使用UIView設置背景圖片,因爲我需要背景圖片來垂直平鋪。我將UIView的框架設置爲與我的像素寬度和png高度相同的大小,但圖像偏移並縮放不正確。難道是因爲圖像有一些透明的像素?我嘗試了以下內容:UIView的背景縮放不正確,偏移

_view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]; 
_view.opaque = NO; 
_view.contentMode = UIViewContentModeScaleAspectFit; 
//_view.layer.contentsGravity = kCAGravityTop; 
+0

可以顯示屏幕截圖嗎? – 2012-01-31 10:53:25

回答

1

您可能會發現僅製作UIView的子類更容易。在子類中,覆蓋drawRect:以使用drawAsPatternInRect:來繪製圖像。該方法將通過平鋪圖像來填充視圖:

- (void)drawRect:(CGRect)dirtyRect { 
    [self.tileImage drawAsPatternInRect:self.bounds]; 
} 
0

我認爲這是因爲您使用圖像作爲背景顏色。 如果你使用了一個imageview,並且將它作爲子視圖添加,就像這樣。

//編輯垂直平鋪

int y = 0; 
int imgsize = 100; //in pixels 
for (i =0; i<max; i++) { //max is the number of tiles you want 
UIImageView *img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]]; 
img.frame = CGRectMake(0,y+imgsize,100,100); 
y+=imgsize; //increase y each time(new starting point) 
[_view addSubview:img]; 
} 

可能不是做的最好的方式,但它會奏效。

+0

謝謝,但我怎麼才能得到圖像瓷磚? – prostock 2012-01-31 17:23:30

+0

對不起,我沒有正確地閱讀這個問題。編輯我的原始答案,給你一個平鋪效果。 – 2012-01-31 18:42:13

+0

使用'[的UIColor colorWithPatternImage:圖片]'將有好得多的性能 - 這是平鋪圖像的非常強力的方式,但它避開了所有的最好的CoreGraphics中例程的繪製圖像('[圖像resizableImageWithCapInsets:{0,0 ,0,0} resizingMode:UIImageResizingModeTile]'可以輕而易舉地創建平鋪圖像) – colinta 2013-02-14 15:19:52