2011-02-23 10 views
4

보라 (위 주석)이있는 UIImageView 사용iOS - UIImageView는 늘릴 수 있지만 UIButton은 늘릴 수 없습니까?

//UIImageView* stretchTest = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]]; 
//[self addSubview:stretchTest]; 


UIButton *stretchTest = [UIButton buttonWithType:UIButtonTypeCustom]; 
[stretchTest setFrame:CGRectMake(0, 0, 400, 100)]; 
[stretchTest setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal]; 
[self addSubview:stretchTest]; 

stretchTest.contentStretch = CGRectMake(0.5, 0.5, 0, 0); 
stretchTest.contentMode = UIViewContentModeScaleToFill; 

CGRect frame = stretchTest.frame; 
frame.size.height = 300; 
stretchTest.frame = frame; 

, 이미지가 적절하게 뻗어 - 이미지의 중심 화소가 연신되기 때 둥근 모서리는 정확한 반경을 유지한다.

UIButton을 사용하면 이미지가 제대로 늘어나지 않습니다. 모서리 반지름은 유지되지 않고 추한 상태가됩니다.

UIImageView와 UIButton은 모두 UIView의 하위 클래스입니다. 왜 버튼의 크기가 imageView와 다르게됩니까?

답변

11

UIButton의 작동 방식을 전제로합니다. UIImageView와 같은 방식으로 구현되지 않습니다. UIImageView는 하위 뷰가없는보기이며 내용은 이미지입니다. UIButton은 다르며 작동 방식은 개인 구현 세부 사항입니다.

버튼에서 이미지를 적절하게 늘리려면 -[UIImage stretchableImageWithLeftCapWidth:topCapHeight:]을 사용하여 이미지를 늘려야하는 방법을 알고있는 UIImage를 가져와야합니다. 전경 이미지와 배경 이미지 - 당신은 단지 중간 픽셀을 스트레칭하고 싶다면, 당신은 UIButton가 표시 할 수있는 이미지의 두 가지 유형

UIImage *image = [UIImage imageNamed:@"image.png"]; 
image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)]; 
+0

ok ... 작동합니다. Apple에 따르면 위의 내용을 사용하려고했기 때문에 "contentStretch 속성을 사용하면 뷰의 배경을 지정할 때 stretchable UIImage 객체를 만드는 것이 좋습니다." UIView의 하위 클래스가이 속성을 사용할 수 있거나 사용할 수없는 것에 대해서는 언급하지 않았습니다. – sol

+1

버튼에 사용할 수있는 contentStretch는 UIImageViews를 자체에 삽입하고 배경 이미지 (및 contentStretch)를 그 안에 복사하는 UIButton 하위 클래스 인 필자가 작성한 충분한 기능입니다 (지금 두 번!). 그것은 어렵지 않습니다. 유일한 작은 문제는 'LayoutSubviews'를 오버라이드하여 imageViews를 뒤로 이동시켜 단추의 배경이 아닌 이미지 및 제목 레이블 뒤에 표시되도록하는 것입니다. – rgeorge

0

같은 것을 사용할 수 있습니다. 버튼의 배경 이미지는 버튼의 배경 텍스처를 대체 할 것으로 예상됩니다. 따라서 전체 배경을 채우기 위해 늘어납니다. 버튼의 전경 이미지는 텍스트 옆에 표시되거나 표시되지 않을 수있는 아이콘이어야합니다. 스트레칭되지 않습니다. 프레임이 이미지보다 작 으면 이 될 수는 있지만 늘어나지는 않습니다.

은 A 버튼의 전경과 배경 이미지는 다음과 같은 코드로 설정할 수 있습니다 : 기본적으로

// stretchy 
[self setBackgroundImage:backgroundImage forState:UIControlStateNormal]; 

// not stretchy 
[self setImage:forgroundImage forState:UIControlStateNormal]; 

는 버튼의 backgroundImage 이미지를 스트레칭 scaleToFill을 사용합니다. 캡 인세 트를 사용하여 이미지를 늘려야하는 경우에는 다음과 같이 backgroundImage에 할당하기 전에 이미지에 이미지를 설정해야합니다.

UIImage *image = [UIImage imageNamed:@"bg_image.png"]; 

/* This assumes your image will have a 1px column and 1px row of pixels 
    in the horizontal and vertical middle of the image that should be 
    stretchable. If that's not the case (such as asymetrical buttons) 
    you need to adjust the caps */ 
image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) 
       topCapHeight:floorf(image.size.height/2)]; 
[self setBackgroundImage:image forState:UIControlStateNormal]; 
관련 문제