簡體   English   中英

在UIImageView中調整UIImage的大小

[英]Resizing UIImage in UIImageView

我正在嘗試創建一個帶有一些圖像的UIPickerView,但我似乎無法弄清楚如何使圖像適合視圖(現在它們太大而且相互重疊)。

我正在嘗試使用函數在繪制時調整每個圖像的大小,但是在調用函數時我遇到錯誤,盡管程序編譯並運行正常(圖像沒有調整大小除外)。 調整大小功能和初始化函數是:

-(UIImage *)resizeImage:(UIImage *)image width:(int)width height:(int)height {
    NSLog(@"resizing");
    CGImageRef imageRef = [image CGImage];
    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);

    //if (alphaInfo == kCGImageAlphaNone)
    alphaInfo = kCGImageAlphaNoneSkipLast;

    CGContextRef bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(imageRef), 
                                                4 * width, CGImageGetColorSpace(imageRef), alphaInfo);
    CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage *result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);
    CGImageRelease(ref);

    return result;  
}

- (void)viewDidLoad {
    UIImage *h1 = [UIImage imageNamed:@"h1.png"];

    h1 = [self resizeImage:h1 width:50 height: 50];

    UIImageView *h1View = [[UIImageView alloc] initWithImage:h1];

    NSArray *imageViewArray = [[NSArray alloc] initWithObjects:
                                h1View, nil];

    NSString *fieldName = [[NSString alloc] initWithFormat:@"column1"];
    [self setValue:imageViewArray forKey:fieldName];
    [fieldName release];
    [imageViewArray release];

    [h1View release];
}

控制台輸出:

TabTemplate [29322:207]調整大小

TabTemplate [29322]:CGBitmapContextCreate:不支持的顏色空間

TabTemplate [29322]:CGContextDrawImage:無效的上下文

TabTemplate [29322]:CGBitmapContextCreateImage:無效的上下文

我無法弄清楚出了什么問題。 任何幫助是極大的贊賞。

如果使用UIImageViewcontentMode屬性,則不需要調整UIImage大小。

    myImageView.contentMode  = UIViewContentModeScaleAspectFit;

或者如果您仍想調整UIImage的大小,請查看下面的SO帖子。

調整UIImage的大小而不將其完全加載到內存中?

UIImage:調整大小,然后裁剪

使用下面的內容使用寬高比縮放圖像,然后將圖像剪切為imageview的邊界。

imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES; 

在迅速的情況下

imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
UIImage *image = [UIImage imageNamed:@"myImage"];
    [image drawInRect: destinationRect];
    UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);

暫無
暫無

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

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