簡體   English   中英

調整UIImage的大小並更改UIImageView的大小

[英]Resize UIImage and change the size of UIImageView

我有這個UIImageView ,我有它的最大高度和最大寬度的值。 我想要實現的是我想拍攝圖像(具有任何寬高比和任何分辨率)並且我希望它適合邊框,因此圖片不會超過它們,但它可以根據需要縮小它們。 (圖中標記為紅色):

在此輸入圖像描述

現在圖像正確地適合所需的大小,但我有兩個擔憂: UIImageView不等於調整大小的圖像的大小,因此留下紅色背景(我不想要那樣)2。如果圖像較小我的UIImageView的高度沒有調整到更小,它保持相同的高度。

這是我的代碼,我知道它的錯誤:

UIImage *actualImage = [attachmentsArray lastObject];
UIImageView *attachmentImageNew = [[UIImageView alloc] initWithFrame:CGRectMake(5.5, 6.5, 245, 134)];
attachmentImageNew.image = actualImage;
attachmentImageNew.backgroundColor = [UIColor redColor];
attachmentImageNew.contentMode = UIViewContentModeScaleAspectFit;

那么我如何動態地改變UIImageView.image的大小,而不是整個UIImageView的大小,從而使其大小完全可以調整其內容。 任何幫助將不勝感激,謝謝!

當您獲得已調整大小的圖像的寬度和高度在UIViewContentModeScaleAspectFit之后獲取已調整大小的圖像的寬度時 ,您可以調整imageView的大小:

imageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight);
imageView.center = imageView.superview.center;

我沒有檢查它是否有效,但我認為一切都應該沒問題

- (UIImage *)image:(UIImage*)originalImage scaledToSize:(CGSize)size
{
    //avoid redundant drawing
    if (CGSizeEqualToSize(originalImage.size, size))
    {
        return originalImage;
    }

    //create drawing context
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);

    //draw
    [originalImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];

    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //return image
    return image;
}

這是使用擴展的Rajneesh071答案的Swift等價物

UIImage {
  func scaleToSize(aSize :CGSize) -> UIImage {
    if (CGSizeEqualToSize(self.size, aSize)) {
      return self
    }

    UIGraphicsBeginImageContextWithOptions(aSize, false, 0.0)
    self.drawInRect(CGRectMake(0.0, 0.0, aSize.width, aSize.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
  }
}

用法:

let image = UIImage(named: "Icon")
item.icon = image?.scaleToSize(CGSize(width: 30.0, height: 30.0))

使用下面的類別,然后將Quartz中的邊框應用到您的圖像中:

[yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[yourimage.layer setBorderWidth:2];

類別:UIImage + AutoScaleResize.h

#import <Foundation/Foundation.h>

@interface UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;

@end

的UIImage + AutoScaleResize.m

#import "UIImage+AutoScaleResize.h"

@implementation UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor > heightFactor)
        {
            scaleFactor = widthFactor; // scale to fit height
        }
        else
        {
            scaleFactor = heightFactor; // scale to fit width
        }

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
        {
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
    }

    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil)
    {
        NSLog(@"could not scale image");
    }

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    return newImage;
}

@end

如果你有圖像的大小,為什么不設置圖像視圖的frame.size為這個大小?

編輯 - -

好的,所以看到你的評論我建議:

UIImageView *imageView;
//so let's say you're image view size is set to the maximum size you want

CGFloat maxWidth = imageView.frame.size.width;
CGFloat maxHeight = imageView.frame.size.height;

CGFloat viewRatio = maxWidth / maxHeight;
CGFloat imageRatio = image.size.height / image.size.width;

if (imageRatio > viewRatio) {
    CGFloat imageViewHeight = round(maxWidth * imageRatio);
    imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
}
else if (imageRatio < viewRatio) {
    CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
    imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
} else {
    //your image view is already at the good size
}

此代碼會將圖像視圖的大小調整為其圖像比例,並將圖像視圖定位到與“默認”位置相同的中心。

PS:我希望你設置imageView.layer.rasterizationScale = [UIScreen mainScreen].scale; imageView.layer.shouldRasterise = YESimageView.layer.rasterizationScale = [UIScreen mainScreen].scale;

如果您正在使用CALayer陰影效果;)它將極大地提高您的UI性能。

我想你想要的是一種不同的content mode 嘗試使用UIViewContentModeScaleToFill 如果需要,這將通過更改內容的寬高比來縮放內容以適合您的UIImageView的大小。

查看官方文檔上的content mode部分,以更好地了解可用的不同內容模式(用圖像說明)。

   if([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:@"URL STRING1"]])
   {
       NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:@"URL STRING1"]];

       UIImage *tempImage=[self imageWithImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key] scaledToWidth:cell.imgview.bounds.size.width];
       cell.imgview.image=tempImage;

   }
   else
   {
       [cell.imgview sd_setImageWithURL:[NSURL URLWithString:@"URL STRING1"] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
        {
            UIImage *tempImage=[self imageWithImage:image scaledToWidth:cell.imgview.bounds.size.width];
            cell.imgview.image=tempImage;
//                [tableView beginUpdates];
//                [tableView endUpdates];

        }];
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM