無論任何縮放涉及兩個不同尺寸的圖像可以不看完全一樣。但是,您可以將圖像分爲三部分:左角,中間部分(僅平行線)和右角。
現在要創建不同大小的圖像視圖,您需要保持左側和右側部分不變,並縮放中間部分,只要保持高度不變,就不會看起來扭曲。
請注意,我已將fitInRect
的高度設置爲77,因爲這是原始圖像高度。您可以將其更改爲44,但請將所有圖像視圖的編號保持不變。 最後,widthToPreserve
必須至少爲34(這意味着整個矩形寬度必須是68或更多),因爲那是原始圖像中圓角邊緣的寬度。
當然,如果您的目標圖像視圖高度爲44,您可以通過縮小圖像來簡單實現所有這些。
此代碼的工作:
-(void)viewDidAppear:(BOOL)animated
{
UIImage *img = [UIImage imageNamed:@"img"];
UIImageView *view1 = [self getImageViewFromImage:img widthToPreserve:34 fitInRect:CGRectMake(20, 20, 100, 77)];
UIImageView *view2 = [self getImageViewFromImage:img widthToPreserve:34 fitInRect:CGRectMake(20, 120, 250, 77)];
[self.view addSubview:view1];
[self.view addSubview:view2];
}
-(UIImageView*)getImageViewFromImage:(UIImage*)image widthToPreserve:(float)width fitInRect:(CGRect)rect
{
CGImageRef left, middle, right;
CGRect leftRect, middleRect, rightRect;
UIImage *leftImage, *middleImage, *rightImage;
UIImageView *leftView, *middleView, *rightView;
// calculate CGRect values for the original image
leftRect = CGRectMake(0, 0, width, image.size.height);
middleRect = CGRectMake(width, 0, image.size.width - 2*width, image.size.height);
rightRect = CGRectMake(image.size.width - width, 0, width, image.size.height);
left = CGImageCreateWithImageInRect([image CGImage], leftRect);
middle = CGImageCreateWithImageInRect([image CGImage], middleRect);
right = CGImageCreateWithImageInRect([image CGImage], rightRect);
leftImage = [UIImage imageWithCGImage:left];
middleImage = [UIImage imageWithCGImage:middle];
rightImage = [UIImage imageWithCGImage:right];
leftView = [[UIImageView alloc] initWithImage:leftImage];
middleView = [[UIImageView alloc] initWithImage:middleImage];
rightView = [[UIImageView alloc] initWithImage:rightImage];
//make your image subviews, with scaling on the middle view
[leftView setFrame:CGRectMake(0, 0, width, rect.size.height)];
[middleView setFrame:CGRectMake(width, 0, rect.size.width - 2*width, rect.size.height)];
[rightView setFrame:CGRectMake(rect.size.width - width, 0, width, rect.size.height)];
//add your 3 subviews into a single image view
UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
[imgView addSubview:leftView];
[imgView addSubview:middleView];
[imgView addSubview:rightView];
CGImageRelease(left);
CGImageRelease(middle);
CGImageRelease(right);
return imgView;
}
截圖:
與圖像視圖的問題是,它們比原圖像的情況下(高)(以及第一窄太)。可調整大小的圖像比原始圖像要大。 – rmaddy