图像视图和图像宽高比的差异

时间:2017-04-10 06:15:41

标签: ios uiimageview bounds aspect-fit

我在UIView上添加了一个Imageview,并设置了属性AspectToFit。根据应用程序的要求,我需要在imageview上再添加一个图像。

iPhone 6s Plus

    float width;
    float height;
    float x;
    float y;

    CGSize imageViewSize =  self.getImageView.bounds.size;// self.getImageView.frame.size;
    CGSize imageSize = self.getImage.size;
    CGFloat minFactor = imageViewSize.width / imageSize.width;
    if (imageViewSize.height / imageSize.height < minFactor)
    {
        minFactor = imageViewSize.height / imageSize.height;
    }
    CGRect frame = self.getImageView.frame;
    NSLog(@"view height..%@",NSStringFromCGRect (frame));
    CGSize resultSize = CGSizeMake(minFactor * imageSize.width, minFactor * imageSize.height);
    UIImage *newimage =  [self imageWithImage:self.getImage scaledToSize:resultSize];
    float mainwidth = imageViewSize.width;
    float mainheight = imageViewSize.height;

    float imagewidth = newimage.size.width;
    float imageheight = newimage.size.height;

    _widthdiff = mainwidth-imagewidth;
    _heightdiff = mainheight-imageheight;

    x = self.view.frame.size.width-width-0-_widthdiff/2;
    y = self.view.frame.size.height-height-116-_heightdiff/2;

imageview = [[UIImageView alloc]
                 initWithFrame:CGRectMake(x, y, width, height)];
    [imageview setContentMode:UIViewContentModeScaleAspectFit];

此代码适用于除iPhone(iPhone 6 Plus,iPone 7 Plus)以外的所有设备。正如我所看到的,仅在设备的大小上存在问题。

是否有不同的方法来计算imageview和正确图像之间的差异或比例? 请指教。

请参阅附图iPhone 5s

1 个答案:

答案 0 :(得分:1)

我们可以通过计算旧图像的大小来添加新图像,然后根据需要将其添加到UIView。

    CGSize imageViewSize =   self.getImageView.frame.size;
    CGSize imageSize = self.getImage.size;
    CGFloat minFactor = imageViewSize.width / imageSize.width;
    if (imageViewSize.height / imageSize.height < minFactor)
    {
        minFactor = imageViewSize.height / imageSize.height;
    }
    CGSize resultSize = CGSizeMake(minFactor * imageSize.width, minFactor * imageSize.height);

    UIImage *newimage =  [self imageWithImage:self.getImage scaledToSize:resultSize];
self.duplicateimageview = [[UIImageView alloc]
                                   initWithFrame:CGRectMake(self.view.frame.size.width/2-newimage.size.width/2, self.view.frame.size.height/2-newimage.size.height/2, newimage.size.width, newimage.size.height)];
        [self.view addSubview:self.duplicateimageview];
        self.duplicateimageview.image = newimage;    

- (UIImage*)imageWithImage:(UIImage*)image
              scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}