0

我无法解决这个问题。加载图像,转换为CGImageRef. 尝试获取位图上下文并在屏幕上渲染。

 NSURL *imageFileURL = [NSURL fileURLWithPath:stringIMG];

   CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);
   CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);

    NSInteger bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
    NSInteger bitsPerPixel = CGImageGetBitsPerPixel(imageRef);
    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
    NSInteger bytesPerRow = CGImageGetBytesPerRow(imageRef);
    NSInteger width = CGImageGetWidth(imageRef);
    NSInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorspace = CGImageGetColorSpace(imageRef);

    size_t rawData = bytesPerRow*height;
    unsigned char *data = malloc(rawData);
    memset(data2, 0, rawData);

     CGContextRef context = CGBitmapContextCreate(data, width, height, bitsPerComponent, bytesPerRow, colorspace, bitmapInfo);


    CGImageRef imageRef2 = CGBitmapContextCreateImage(context);

   // CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef2);
    UIImage *result = [UIImage imageWithCGImage:imageRef2];//if i do like this i got white empty screen

    UIImageView *image = [[UIImageView alloc] initWithImage:result];
    [self.view addSubview:image];// if i do like this i got black rectangle on the white screen

我不知道。我通过断点检查上下文不为空。我不知道我该怎么办。请也许有人可以帮助我吗?

4

1 回答 1

0

类别将其添加到 UIImage 以使用 CoreGraphics 调整大小

UIImage+调整大小.h

#import <UIKit/UIKit.h>

@interface UIImage (Resizing)

-(UIImage*)resizedImageWithSize:(CGSize)size;

@end

UIImage+调整大小.m

#import "UIImage+Resizing.h"

@implementation UIImage (Resizing)

-(UIImage*)resizedImageWithSize:(CGSize)size {


    CGImageRef cgImage = [self CGImage];

    size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage);
    size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage);
    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(cgImage);

    CGContextRef context = CGBitmapContextCreate(nil, size.width, size.height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);

    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);

    CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), cgImage);

    CGImageRef resizedImageRef = CGBitmapContextCreateImage(context);

    UIImage *resizedImage = [UIImage imageWithCGImage:resizedImageRef];

    CFRelease(resizedImageRef);
    CFRelease(context);

    return resizedImage;

}

@end
于 2016-12-07T13:09:05.767 回答