在开发Ipad应用中,如果需要显示图片到窗口,首先要确定在哪一个UIView中显示,再确定从哪里获取图片,下面实例代码为几种不同方式加载图片的设定
#import <UIKit/UIKit.h>
#import "ImageHelper-Files.h"
#define COOKBOOK_PURPLE_COLOR [UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]
//实现宏定义,设定当前导航窗口右上角的按钮和事件代理对象
#define BARBUTTON(TITLE, SELECTOR) [[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR] autorelease]
//设定当前窗口的视图 图片为X
#define SETIMAGE(X) [(UIImageView *)self.view setImage:X]
const int NUM_OPTIONS = 4;
int which = 0;
//视图控制器类
@interface TestBedViewController : UIViewController
@end
//视图控制器类实现
@implementation TestBedViewController
//按钮的事件代理方法,
- (void) action: (id) sender
{
switch (which)
{
case 0:
// 从互联网URL获取UIImage,并加载到当前窗口
self.title = @"URL-based image";
SETIMAGE([ImageHelper imageFromURLString:@"http://imgsrc.baidu.com/baike/abpic/item/9dc3cf58ab414192810a1836.jpg"]);
break;
case 1:
// 使用当前项目中的资源
self.title = @"imageNamed:";
SETIMAGE([UIImage imageNamed:@"BFlyCircle.png"]);
break;
case 2:
// Use the Image Helper version of imageNamed:
self.title = @"Image Helper";
SETIMAGE([ImageHelper imageNamed:@"icon.png"]);
break;
case 3:
// 加载文件中的图片
self.title = @"Contents of file";
SETIMAGE([UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cover320x416" ofType:@"png"]]);
break;
default:
break;
}
NSString *next = [NSString stringWithFormat:@"Example %d", (which = (which + 1) % NUM_OPTIONS) + 1];
self.navigationItem.rightBarButtonItem = BARBUTTON(next, @selector(action:));
}
//当前窗口加载完成后初始化右上角的按钮 和 事件代理
- (void) viewDidLoad
{
self.navigationController.navigationBar.tintColor = COOKBOOK_PURPLE_COLOR;
self.navigationItem.rightBarButtonItem = BARBUTTON(@"Example 1", @selector(action:));
}
@end
//应用程序代理类
@interface TestBedAppDelegate : NSObject <UIApplicationDelegate>
@end
//应用程序代理类实现
@implementation TestBedAppDelegate
//当程序启动完成创建一个UIWindow,设定一个导航的视图,并开始用户交互
- (void)applicationDidFinishLaunching:(UIApplication *)application {
UIWindow *window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[TestBedViewController alloc] init]];
[window addSubview:nav.view];
[window makeKeyAndVisible];
}
@end
//程序入口函数,将当前应用程序的生命周期绑定一个TestBedAppDelegate类的实例
int main(int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
[pool release];
return retVal;
}
---------------------通过以上接口可以看到,加载图片主要使用以下方法
1。加载互联网中的图片
[UIImageimageWithContentsOfFile:[[NSBundlemainBundle] pathForResource:@"cover320x416"ofType:@"png"]];
2。加载项目资源图片
[UIImageimageNamed:@"BFlyCircle.png"];
3。加载文件中的图片 //路径获取
[UIImageimageWithContentsOfFile:[[NSBundlemainBundle] pathForResource:@"cover320x416"ofType:@"png"]];