2012-03-09 120 views
0

我有一個自定義的UIView。所以myView類擴展UIView。在initWithFrame:(CGRect)框架方法中,我將UIImage的UIImageView設置爲背景圖像。iPhone:更改UIImageView框架

- (id)initWithFrame:(CGRect)frame 
{ 
self = [super initWithFrame:frame]; 
if (self) { 
     self.bgImage = [[[UIImageView alloc] initWithFrame: 
      CGRectMake(0, 0, frame.size.width , frame.size.height)] autorelease]; 
     int stretchableCap = 20; 
     UIImage *bg = [UIImage imageNamed:@"myImage.png"]; 
     UIImage *stretchIcon = [bg 
      stretchableImageWithLeftCapWidth:stretchableCap topCapHeight:0]; 
    [self.bgImage setImage:stretchIcon]; 
} 
return self; 
} 

所以當我創建我的視圖時,一切都很好。

MyCustomView *customView = [[MyCustomView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)]; 

但是,如果我想改變我的觀點尺寸更大或更小:

customView.frame = CGRectMake(10, 10, 50, 50)]; 

然後我和我的背景圖片的問題。因爲它的大小沒有改變。該怎麼辦 ?何改變圖像大小與視圖框架?

回答

0

所以這些建議是對的。我應該添加自動調整掩碼。現在我的initWithFrame看起來像這樣:

- (id)initWithFrame:(CGRect)frame 
{ 
self = [super initWithFrame:frame]; 
if (self) { 
     self.bgImage = [[[UIImageView alloc] initWithFrame: 
     CGRectMake(0, 0, frame.size.width , frame.size.height)] autorelease]; 
    int stretchableCap = 20; 
    UIImage *bg = [UIImage imageNamed:@"myImage.png"]; 
    UIImage *stretchIcon = [bg 
     stretchableImageWithLeftCapWidth:stretchableCap topCapHeight:0]; 
[self.bgImage setImage:stretchIcon]; 
self.bgImage.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 
self.autoresizesSubviews = YES; 
} 
return self; 
} 
0

嘗試設置UIImageView的自動識別掩碼,它將根據超級視圖的大小更改來調整大小。

+0

代碼示例,請 – Jim 2012-03-09 09:10:45

+0

customView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; – tim 2012-03-09 09:13:22

+0

我可以只把self.autoresizesSubviews = YES;到initWithFrame方法? – Jim 2012-03-09 09:14:41

0

我的建議是使用更新功能來更新您的自定義視圖,當你要更改的框架:

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     [self UpdateViewWithFrame:frame]; 
    } 
    return self; 
} 

- (void)UpdateViewWithFrame:(CGRect)frame 
{ 
    self.frame = frame;//set frame 
    if(!self.bgImage) 
    { 
     //initialize your imageview 
     self.bgImage = [[[UIImageView alloc] initWithFrame: 
      CGRectMake(0, 0, frame.size.width , frame.size.height)] autorelease]; 
    } 
    int stretchableCap = 20; 
    UIImage *bg = [UIImage imageNamed:@"myImage.png"]; 
    UIImage *stretchIcon = [bg 
     stretchableImageWithLeftCapWidth:stretchableCap topCapHeight:0]; 
    [self.bgImage setImage:stretchIcon]; 
} 

當你想改變框架,只是稱這個function.Have一試的人。

+0

所以如果我想改變框架,我應該再次調用initWithFrame?壞主意 – Jim 2012-03-09 09:27:56

+0

不是initWithFrame只是UpdateViewWithFrame'[customView UpdateViewWithFrame:CGRectMake(10,10,50,50)]' – Bonny 2012-03-09 09:30:08

+0

我認爲自動調整的想法更好 – Jim 2012-03-09 09:39:19

0

正確設置圖像視圖所需的Autoresizingmask屬性屬性,因爲它必須與視圖框一起調整。