如何将图片设置为UIImage
对象。
例如:
UIImage *img = [[UIImage alloc] init];
[img setImage:[UIImage imageNamed:@"anyImageName"]];
我的UIImage
对象在.h
文件中声明并在init
方法中分配,我需要在viewDidLoad
方法中设置图像。有什么想法吗?
如何将图片设置为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
参数
name
文件的名称。如果这是第一次加载该图像,则该方法会在应用程序的主要捆绑包中查找指定名称的图像。
返回值
指定文件的图像对象;如果该方法未能找到指定的图像,则返回 nil。
讨论
此方法在系统缓存中查找具有指定名称的图像对象,如果存在,则返回该对象。如果匹配的图像对象尚未缓存在系统中,则此方法会从指定文件加载图像数据、缓存数据,然后返回结果对象。
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image Name"]] ;
然后将其添加到你的视图中:
[self.view addSubView: imageView];
只需按照以下步骤操作
UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];
这一行有一个错误:
[img setImage:[UIImage imageNamed@"anyImageName"]];
应该是这样的:
[img setImage:[UIImage imageNamed:@"anyImageName"]];
UIImage *img = [UIImage imageNamed@"aImageName"];
可能是:
UIImage *img = [[UIImage alloc] init];
当您想要更改图像时:
img = [UIImage imageNamed:@"nameOfPng.png"];
但是对象在内存中的位置不同,但如果使用指针,则相同的指针将指向最后加载的图像。
-released
也会产生选择器未找到的错误。 - vikingosegundo您可以通过以下两种方式之一在UIImage对象中设置图像:
UIImage *imageObject = [UIImage imageNamed:@"imageFileName"];
但是,通过这种方式初始化UIImage
对象时,即使您将其设置为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];
你不能分配UIImage,这是不可能的。 使用UIImageView分配的正确代码:
UIImageView *_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"something.png"]] ;
绘制图像:
CGContextDrawImage(context, rect, _image.image.CGImage);
[UIImage imageNamed:image]
,则图像将被缓存并占用内存。因此,除非您计划在许多地方使用相同的图像,否则应该使用imageWithContentsOfFile:
和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];