如何设置图像到UIImage
如何将图像设置为UIImage
对象。 例如:
UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]];
我的UIImage
对象在.h
文件中声明并在init
方法中分配,我需要在viewDidLoad
方法中设置图像。 有任何想法吗?
UIImage *img = [UIImage imageNamed:@"anyImageName"];
imageNamed:
返回与指定文件名关联的图像对象。+ (UIImage *)imageNamed:(NSString *)name
参数
名称
文件的名称。 如果这是第一次加载图像,则该方法在应用程序的主包中查找具有指定名称的图像。
返回值
指定文件的图像对象,如果方法找不到指定的图像,则为nil。讨论
此方法在系统caching中查找具有指定名称的图像对象,并返回该对象(如果存在)。 如果匹配的图像对象不在caching中,则此方法从指定的文件加载图像数据,将其caching,然后返回结果对象。
创build一个UIImageView并添加UIImage:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image Name"]] ;
然后将其添加到您的视图:
[self.view addSubView: imageView];
这条线上有一个错误:
[img setImage:[UIImage imageNamed@"anyImageName"]];
它应该是:
[img setImage:[UIImage imageNamed:@"anyImageName"]];
UIImage *img = [UIImage imageNamed@"aImageName"];
只要按照这个
UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)]; [imgview setImage:[UIImage imageNamed:@"YourImageName"]]; [imgview setContentMode:UIViewContentModeScaleAspectFit]; [self.view addSubview:imgview];
也许:
UIImage *img = [[UIImage alloc] init];
当你想改变图像时:
img = [UIImage imageNamed:@"nameOfPng.png"];
但是对象不在内存中的相同位置,但是如果使用指针,则同一个指针将指向加载的最后一个图像。
像vikingosgundo说,但请记住,如果你使用[UIImage imageNamed:image]
那么图像被caching,并消耗内存。 因此,除非您计划在许多地方使用相同的图像,否则应该使用imageWithContentsOfFile:
和imageWithData:
加载图像imageWithData:
这将为您节省大量的内存,并加速您的应用程序。
首先声明UIImageView并给它框架
UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake( 10.0f, 15.0f, 40.0f,40.0f )]; [imageView setBackgroundColor: [UIColor clearColor]]; [imageView setImage:[UIImage imageNamed:@"comments_profile_image.png"]]; [self.view addSubview: imageView];
你可以通过以下方式在UIImage对象中设置图像:
-
UIImage *imageObject = [UIImage imageNamed:@"imageFileName"];
但通过像这样初始化UIImage
对象,图像总是存储在高速缓冲存储器中,即使你使它像nil
imageObject=nil;
最好遵循这一点:
-
NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"imageFilename" ofType:@"imageFile_Extension"];
UIImage *imageObject = [UIImage imageWithContentsOfFile:imageFilePath];
例子: NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"abc" ofType:@"png"];
UIImage *imageObject = [UIImage imageWithContentsOfFile:imageFilePath];
只是改变这一行
[img setImage:[UIImage imageNamed:@"anyImageName"]];
以下行
img = [UIImage imageNamed:@"anyImageName"];
你不能分配UIImage,这是不可能的。 正确的代码与UIImageView分配:
UIImageView *_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"something.png"]] ;
绘制图像:
CGContextDrawImage(context, rect, _image.image.CGImage);
试试这个代码100%的工作….
UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)]; imageview.image = [UIImage imageNamed:@"myimage.jpg"]; [self.view addSubview:imageview];