iPhone:更改UIImageView框架

时间:2012-03-09 09:08:15

标签: iphone uiview uiimageview

我有一个自定义的UIView。所以myView类扩展了UIView。在initWithFrame:(CGRect)框架方法中,我将UIVmageView设置为我的UIView作为背景图像。

- (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)];

然后我的背景图片有问题。因为它的大小没有改变。该怎么办 ?何与视图框一起改变bg图像大小?

4 个答案:

答案 0 :(得分:0)

尝试设置UIImageView的自动调整遮罩,它会根据超级视图的大小变化调整大小。

答案 1 :(得分: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];
}

当你想要改变框架时,只需调用此功能。试一试。

答案 2 :(得分:0)

正确设置imageview所需的Autoresizingmask属性,因为它必须与视图框一起调整。

答案 3 :(得分: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;
}