《Instant OpenCV for iOS》 学习笔记(2)

从工程目录(supporting)显示图像

ios应用程序在supporting目录存放图像文件。本文我们学习如何添加图像文件到资源文件夹,如何加载图像文件到UIImage对象并显示。我们将会用到UIImageView组件。

准备

  • 准备一张照片文件 http://lenna.org 这张叫做lenna的照片在各种图像处理教科书中被使用到,简直可以说是图像处理里的hello word御用照片了。从这个网站可以了解到这张照片的来历:)。

步骤

  • 新建一个工程具体步骤详见《Instant OpenCV for iOS》 学习笔记(1))或者直接在原来的工程上继续开发(我选择后者)。

  • 拖入下载的图片文件到工程supporting Files 目录下2015-10-03-01.jpg

  • 加入ImageView 到我们的View视图中: 打开StoryBoard Editor -> 从Object Library 中选择Image View 组件拖到Story Board的View中 2015-10-03-02.jpg
  • 在ViewController.h中添加变量image:
1
2
3
4
5
6
7
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
UIImage* image;
}

@end
  • 然后打开storyBoard Editor 并调出Assistant Editor 并在Assistant Editor 中打开ViewController.h 。此时Xcode的界面显示左右两部分区域。左边是UIImageView的StoryBoard,而右面是显示ViewController.h的Assistant Editor。
  • 从左边StoryBoard按住Ctrl 鼠标按住选择UIImageView 拖到右边的ViewController.h代码界面中。2015-10-03-03.jpg
  • 在弹出的对话框中输入变量名称“imageView”。2015-10-03-04.jpg
  • 自动生成代码后,ViewController.h的代码如下:
1
2
3
4
5
6
7
8
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
UIImage* image;
}
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end
  • 在ViewController.m中添加代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize imageView;

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
image = [UIImage imageNamed:@"lena_std.tif"];
if (image!=nil) {
imageView.image=image;
}
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end
  • 最后 command + r 编译运行
  • 在仿真器上的运行结果
    2015-10-03-05.jpg

注释

  • iOS 的GUI开发使用MVC设计模式。这种模式把应用程序分成界面部分(View)、模型(算法)部分(Model)、控制器(用户交互)部分(Controller)。一些简单的程序只需要View 和 Controller 就可以了,因为逻辑比较简单,无需专门分个Model部分出来。
  • iOS程序的一个View就对应一个storyboard单元。这些单元最终存在*.storyboard 文件中(在本例中,就是Main.storyboard文件)。在Xcode中我们使用集成的Interface Builder工具来编辑 Main.storyboard。
  • 每个view通常对应一个Controller。一般新建一个project时xcode默认创建一个ViewController类(ViewController.h和ViewController.m)。
  • 本例中从storyboard中连线UIImageView到ViewController.h中后xcode自动添加了IBOutlet property用于声明一个接口。IBOutlet 是一个特殊的宏,用于向xcode表明这个声明的property(本例中是UIImageView *imageView)是链接到View单元上。
  • 默认情况下,在controller的接口中添加变量都是自私有的,因此需要对变量添加set和get方法才可以在这个类之外的地方访问这个变量。@property 和 @synthesize 关键字告诉Objective-C编译器自动生成set和get方法。
  • (void)viewDidLoad方法在ViewController加载时被调用。因此在这里添加显示图像的代码。