Gowhich

Durban's Blog

联合(union)

  1. 联合说明和联合变量定义
    联合也是一种新的数据类型, 它是一种特殊形式的变量。
    联合说明和联合变量定义与结构十分相似。其形式为:
    union 联合名{
    数据类型 成员名;
    数据类型 成员名;

    } 联合变量名;
    联合表示几个变量公用一个内存位置, 在不同的时间保存不同的数据类型 和不同长度的变量。
    下例表示说明一个联合a_bc:
1
2
3
4
union a_bc{
int i;
char mm;
};

再用已说明的联合可定义联合变量。
例如用上面说明的联合定义一个名为lgc的联合变量, 可写成:

1
union a_bc lgc;

在联合变量lgc中, 整型量i和字符mm公用同一内存位置。
当一个联合被说明时, 编译程序自动地产生一个变量, 其长度为联合中最大的变量长度。
联合访问其成员的方法与结构相同。同样联合变量也可以定义成数组或指针,但定义为指针时, 也要用”->;”符号, 此时联合访问成员可表示成:
联合名->;成员名
另外, 联合既可以出现在结构内, 它的成员也可以是结构。
例如:

1
2
3
4
5
6
7
8
struct{
int age;
char *addr;
union{
int i;
char *ch;
}x;
}y[10];

若要访问结构变量y[1]中联合x的成员i, 可以写成:

1
y[1].x.i;

若要访问结构变量y[2]中联合x的字符串指针ch的第一个字符可写成:

1
*y[2].x.ch;

若写成”y[2].x.*ch;”是错误的。

结构和联合的区别

结构和联合有下列区别:

  1. 结构和联合都是由多个不同的数据类型成员组成, 但在任何同一时刻, 联合转只存放了一个被选中的成员, 而结构的所有成员都存在。

  2. 对于联合的不同成员赋值, 将会对其它成员重写, 原来成员的值就不存在了, 而对于结构的不同成员赋值是互不影响的。

下面举一个例了来加对深联合的理解。

例4:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
main() {
union { /*定义一个联合*/
int i;
struct { /*在联合中定义一个结构*/
char first;
char second;
}
half;
}
number;
number.i = 0x4241; /*联合成员赋值*/
printf("%c%c\n", number.half.first, mumber.half.second);
number.half.first = 'a'; /*联合中结构成员赋值*/
number.half.second = 'b';
printf("%x\n", number.i);
getch();
}

输出结果为:

1
2
AB
6261

从上例结果可以看出: 当给i赋值后, 其低八位也就是first和second的值;当给first和second赋字符后, 这两个字符的ASCII码也将作为i 的低八位和高八位。

详细错误记录:

1
2
3
4
5
6
./dualview.c:57: error: two or more data types in declaration specifiers
./dualview.c:87: error: conflicting types for ‘show_settings’
./dualview.c:57: error: previous declaration of ‘show_settings’ was here
./dualview.c: In function ‘show_settings1’:
./dualview.c:104: warning: suggest parentheses around comparison in operand of &
./dualview.c:106: warning: suggest parentheses around comparison in operand of &

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* dualview.c -- 位字段和位运算 */
#include <stdio.h>
/* 位字段常量 */
/* 是否透明和是否可见 */
#define YES 1
#define NO 0
/* 边框线的样式 */
#define SOLID 0
#define DOTTED 1
#define DASHED 2
/* 三原色 */
#define BLUE 4
#define GREEN 2
#define RED 1
/* 混合颜色 */
#define BLACK 0
#define YELLOW (RED | GREEN)
#define MAGENTA (RED | BLUE)
#define CYAN (GREEN | BLUE)
#define WHITE (RED | GREEN | BLUE)

/* 位运算中使用的常量 */
#define OPAQUE 0x1
#define FILL_BLUE 0x8
#define FILL_GREEN 0x4
#define FILL_RED 0x2
#define FILL_MASK 0xE
#define BORDER 0x100
#define BORDER_BLUE 0x800
#define BORDER_GREEN 0x400
#define BORDER_RED 0x200
#define BORDER_MASK 0xE00
#define B_SOLID 0
#define B_DOTTED 0x1000
#define B_DASHED 0x2000
#define STYLE_NASK 0x3000

const char * colors[8] = {"black","red","green","blue","magenta","cyan","white"};
struct box_props
{
unsigned int opaque :1;
unsigned int fill_color :3;
unsigned int :4;
unsigned int show_border :1;
unsigned int border_color :3;
unsigned int border_style :2;
unsigned int :2;
};


union Views/* 把数据看做结构或者unsigned short 变量 */
{
struct box_props st_view;
unsigned int ui_view;
}

void show_settings(const struct box_props *pb);
void show_settings1(unsigned short);
char *itobs(int n, char *ps);/* 把short值以二进制字符串的形式显示 */

int main(void)
{
/* 创建 Views对象,初始化结构box view */
union Views box = {{YES, YELLOW, YES, GREEN, DASHED}};
char bin_str[8 * sizeof(unsigned int) + 1];

printf("Original box settings:\n");
show_settings(&box.st_view);
printf("\nBox settings using unsigned int view:\n");
show_settings1(box.ui_view);

printf("bits are %s\n", itobs(box.ui_view,bin_str));
box.ui_view &= ~FILL_MASK;/* 把代表填充色的位清0 */
box.ui_view |= (FILL_BLUE | FILL_GREEN);/* 重置填充色 */
box.ui_view ^= OPAQUE;/* 转置指示是否透明的位 */
box.ui_view |= BORDER_RED;/* 错误的方法 */
box.ui_view &= ~STYLE_NASK;/* 清楚样式位 */
box.ui_view |= B_DOTTED;/* 把样式设置为点 */
show_settings(&box.st_view);
printf("\nBox settings using unsigned int view:\n");
show_settings1(box.ui_view);
printf("bits are %s\n", itobs(box.ui_view,bin_str));
return 0;
}

void show_settings(const struct box_props *pb)
{
printf("Box is %s\n", pb->opaque == YES ? "opaque" : "transparent");
printf("The fill color is %s.\n", colors[pb->fill_color]);
printf("Border %s.\n", pb->show_border == YES ? "shown" : "not shown");
printf("The border color is %s\n", colors[pb->border_color]);
printf("The border style is ");
switch(pb->border_style)
{
case SOLID:printf("solid. \n");break;
case DOTTED:printf("dotted.\n");break;
case DASHED:printf("dashed.\n");break;
default:printf("unknown type.\n");
}
}

void show_settings1(unsigned short us)
{
printf("box is %s.\n", us & OPAQUE == OPAQUE ? "opaque" : "transparent");
printf("The fill color is %s\n", colors[(us >> 1) & 07]);
printf("Border %s.\n", us & BORDER == BORDER ? "shown" : "not shown");
printf("The border style is \n");
switch(us & STYLE_NASK)
{
case B_SOLID : printf("solid.\n");break;
case B_DOTTED : printf("dotted.\n");break;
case B_DASHED : printf("dashed.\n");break;
default:printf("unknown type.\n");
}
printf("The border color is %s.\n", colors[(us >> 9) & 07]);
}

/* 把int转换为二进制字符串 */
char *itobs(int n, char *ps)
{
int i;
static int size = 8 * sizeof(unsigned int);
for (i = size -1; i >= 0; i--,n >>= 1)
{
ps[i] = (01 & n) + '0';
}
ps[size] = '\0';
return ps;
}

匿名函数

提到闭包就不得不想起匿名函数,也叫闭包函数(closures),貌似PHP闭包实现主要就是靠它。声明一个匿名函数是这样:

1
2
$func = function() {    
}; //带结束符

可以看到,匿名函数因为没有名字,如果要使用它,需要将其返回给一个变量。匿名函数也像普通函数一样可以声明参数,调用方法也相同:

1
2
3
4
5
6
$func = function( $param ) {
echo $param;
};
$func( 'some string' );
//输出:
//some string

顺便提一下,PHP在引入闭包之前,也有一个可以创建匿名函数的函数:create function,但是代码逻辑只能写成字符串,这样看起来很晦涩并且不好维护,所以很少有人用。

实现闭包

将匿名函数在普通函数中当做参数传入,也可以被返回。这就实现了一个简单的闭包。
下边有三个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//例一
//在函数里定义一个匿名函数,并且调用它
function printStr() {
$func = function( $str ) {
echo $str;
};
$func( 'some string' );
}
printStr();
//例二
//在函数中把匿名函数返回,并且调用它
function getPrintStrFunc() {
$func = function( $str ) {
echo $str;
};
return $func;
}
$printStrFunc = getPrintStrFunc();
$printStrFunc( 'some string' );
//例三
//把匿名函数当做参数传递,并且调用它
function callFunc( $func ) {
$func( 'some string' );
}
$printStrFunc = function( $str ) {
echo $str;
};
callFunc( $printStrFunc );
//也可以直接将匿名函数进行传递。如果你了解js,这种写法可能会很熟悉
callFunc( function( $str ) {
echo $str;
} );

连接闭包和外界变量的关键字:USE
闭包可以保存所在代码块上下文的一些变量和值。PHP在默认情况下,匿名函数不能调用所在代码块的上下文变量,而需要通过使用use关键字。
换一个例子看看:

1
2
3
4
5
6
7
8
9
10
11
12
13
function getMoney() {
$rmb = 1;
$dollar = 6;
$func = function() use ( $rmb ) {
echo $rmb;
echo $dollar;
};
$func();
}
getMoney();
//输出:
//1
//报错,找不到dorllar变量

可以看到,dollar没有在use关键字中声明,在这个匿名函数里也就不能获取到它,所以开发中要注意这个问题。 有人可能会想到,是否可以在匿名函数中改变上下文的变量,但我发现是不可以的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getMoney() {
$rmb = 1;
$func = function() use ( $rmb ) {
echo $rmb;
//把$rmb的值加1
$rmb++;
};
$func();
echo $rmb;
}
getMoney();
//输出:
//1
//1

原来use所引用的也只不过是变量的一个副本而已。但是我想要完全引用变量,而不是复制。
要达到这种效果,其实在变量前加一个 & 符号就可以了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getMoney() {
$rmb = 1;
$func = function() use ( &$rmb ) {
echo $rmb;
//把$rmb的值加1
$rmb++;
};
$func();
echo $rmb;
}
getMoney();
//输出:
//1
//2

这样匿名函数就可以引用上下文的变量了。如果将匿名函数返回给外界,匿名函数会保存use所引用的变量,而外界则不能得到这些变量,这样形成‘闭包’这个概念可能会更清晰一些。
根据描述改变一下上面的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getMoneyFunc() {
$rmb = 1;
$func = function() use ( &$rmb ) {
echo $rmb;
//把$rmb的值加1
$rmb++;
};
return $func;
}
$getMoney = getMoneyFunc();
$getMoney();
$getMoney();
$getMoney();
//输出:
//1
//2
//3

来源:http://my.oschina.net/u/867608/blog/126694?from=mail-notify

我的MacVim配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
"设置菜单语言
set langmenu=zh_cn

" =========
" 功能函数
" =========
" 获取当前目录
func GetPWD()
return substitute(getcwd(), "", "", "g")
endf


" =========
" 环境配置
" =========

" 保留历史记录
set history=400

" 命令行于状态行
set ch=1
set stl=\ [File]\ %F%m%r%h%y[%{&fileformat},%{&fileencoding}]\ %w\ \ [PWD]\ %r%{GetPWD()}%h\ %=\ [Line]\ %l,%c\ %=\ %P
set ls=2 " 始终显示状态行

" 制表符
set tabstop=4
set expandtab
set smarttab
set shiftwidth=4
set softtabstop=4

" 状态栏显示目前所执行的指令
set showcmd

" 行控制
set linebreak
set nocompatible
set textwidth=80
set wrap

" 行号和标尺
set number
set ruler
set rulerformat=%15(%c%V\ %p%%%)

" 控制台响铃
:set noerrorbells
:set novisualbell
:set t_vb= "close visual bell

" 插入模式下使用 <BS>、<Del> <C-W> <C-U>
set backspace=indent,eol,start

" 标签页
set tabpagemax=20
set showtabline=2

" 缩进
set autoindent
set cindent
set smartindent

" 自动重新读入
set autoread

" 代码折叠
set foldmethod=syntax
"set foldmethod=indent

" 自动切换到文件当前目录
set autochdir

"在查找时忽略大小写
set ignorecase
set incsearch
set hlsearch

"显示匹配的括号
set showmatch

"实现全能补全功能,需要打开文件类型检测
"filetype plugin indent on
"打开vim的文件类型自动检测功能
filetype on

"在所有模式下都允许使用鼠标,还可以是n,v,i,c等
set mouse=a

" 恢复上次文件打开位置
set viminfo='10,\"100,:20,%,n~/.viminfo
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("{1}quot;)|exe("norm '\"")|else|exe "norm {1}quot;|endif|endif

" =====================
" 多语言环境
" 默认为 UTF-8 编码
" =====================
if has("multi_byte")
set encoding=utf-8
" English messages only
"language messages zh_CN.utf-8

if has('win32')
language english
let &termencoding=&encoding
endif

set fencs=ucs-bom,utf-8,gbk,cp936,latin1
set formatoptions+=mM
set nobomb " 不使用 Unicode 签名

if v:lang =~? '^\(zh\)\|\(ja\)\|\(ko\)'
set ambiwidth=double
endif
else
echoerr "Sorry, this version of (g)vim was not compiled with +multi_byte"
endif

" =========
" 图形界面
" =========
if has('gui_running')
" 只显示菜单
set guioptions=mcr

" 高亮光标所在的行
set cursorline

" 编辑器配色
"colorscheme zenburn
"colorscheme dusk

if has("win32")
" Windows 兼容配置
source $VIMRUNTIME/mswin.vim

" f11 最大化
map <f11> :call libcallnr('fullscreen.dll', 'ToggleFullScreen', 0)<cr>

" 字体配置
exec 'set guifont='.iconv('Courier_New', &enc, 'gbk').':h11:cANSI'
exec 'set guifontwide='.iconv('微软雅黑', &enc, 'gbk').':h11'
endif

if has("unix") && !has('gui_macvim')
set guifont=Courier\ 10\ Pitch\ 11
set guifontwide=YaHei\ Consolas\ Hybrid\ 11
endif

if has("mac") || has("gui_macvim")
"set guifont=Courier\ New:h18.00
"set guifontwide=YaHei\ Consolas\ Hybrid:h16.00
"set guifont=Monaco:h16
set guifont=Droid\ Sans\ Mono:h14
set guifontwide=YouYuan:h14
if has("gui_macvim")
"set transparency=4
set lines=200 columns=142

let s:lines=&lines
let s:columns=&columns
func! FullScreenEnter()
set lines=999 columns=999
set fu
endf

func! FullScreenLeave()
let &lines=s:lines
let &columns=s:columns
set nofu
endf

func! FullScreenToggle()
if &fullscreen
call FullScreenLeave()
else
call FullScreenEnter()
endif
endf
endif
endif
endif

" Under the Mac(MacVim)
if has("gui_macvim")

" Mac 下,按 \ff 切换全屏
map <Leader><Leader> :call FullScreenToggle()<cr>

" Set input method off
set imdisable

" Set QuickTemplatePath
let g:QuickTemplatePath = $HOME.'/.vim/templates/'

lcd ~/Desktop/

" 自动切换到文件当前目录
set autochdir

" Set QuickTemplatePath
let g:QuickTemplatePath = $HOME.'/.vim/templates/'


endif

" =========
" 插件
" =========
filetype plugin indent on
" =========
" AutoCmd
" =========
if has("autocmd")
filetype plugin indent on

" 括号自动补全
func! AutoClose()
:inoremap ( ()<ESC>i
:inoremap ) <c-r>=ClosePair(')')<CR>
":inoremap " ""<ESC>i
":inoremap ' ''<ESC>i
:inoremap { {}<ESC>i
:inoremap } <c-r>=ClosePair('}')<CR>
:inoremap [ []<ESC>i
:inoremap ] <c-r>=ClosePair(']')<CR>
endf

func! ClosePair(char)
if getline('.')[col('.') - 1] == a:char
return "\<Right>"
else
return a:char
endif
endf

augroup vimrcEx
au!
autocmd FileType text setlocal textwidth=80
autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("{1}quot;) |
\ exe "normal g`\"" |
\ endif
augroup END

"auto close quotation marks for PHP, Javascript, etc, file
au FileType php,c,python,javascript exe AutoClose()

" Auto Check Syntax
"au BufWritePost,FileWritePost *.js,*.php call CheckSyntax(1)

" JavaScript 语法高亮
au FileType html,javascript let g:javascript_enable_domhtmlcss = 1

" 给 Javascript 文件添加 Dict
if has('gui_macvim') || has('unix')
au FileType javascript setlocal dict+=~/.vim/dict/javascript.dict
else
au FileType javascript setlocal dict+=$VIM/vimfiles/dict/javascript.dict
endif

" 格式化 JavaScript 文件
"au FileType javascript map <f12> :call g:Jsbeautify()<cr>
au FileType javascript set omnifunc=javascriptcomplete#CompleteJS

" 给 CSS 文件添加 Dict
if has('gui_macvim') || has('unix')
au FileType css setlocal dict+=~/.vim/dict/css.dict
else
au FileType css setlocal dict+=$VIM/vimfiles/dict/css.dict
endif

" 增加 ActionScript 语法支持
au BufNewFile,BufRead *.as setf actionscript

" 自动最大化窗口
if has('gui_running')
if has("win32")
au GUIEnter * simalt ~x
"elseif has("unix")
"au GUIEnter * winpos 0 0
"set lines=999 columns=999
endif
endif
endif

"acp 自动补全插件
let g:AutoComplPop_Behavior = {
\ 'c': [ {'command' : "\<C-x>\<C-o>",
\ 'pattern' : ".",
\ 'repeat' : 0}
\ ]
\}


" =========
" 快捷键
" =========
map cal :Calendar<cr>
let NERDTreeWinSize=22
map ntree :NERDTree <cr>
map nk :NERDTreeClose <cr>
map <leader>n :NERDTreeToggle<cr>
map cse :ColorSchemeExplorer

" 标签相关的快捷键 Ctrl
map tn :tabnext<cr>
map tp :tabprevious<cr>
map tc :tabclose<cr>
map <C-t> :tabnew<cr>
map <C-p> :tabprevious<cr>
map <C-n> :tabnext<cr>
map <C-k> :tabclose<cr>
map <C-Tab> :tabnext<cr>

" 新建 XHTML 、PHP、Javascript 文件的快捷键
nmap <C-c><C-h> :NewQuickTemplateTab xhtml<cr>
nmap <C-c><C-p> :NewQuickTemplateTab php<cr>
nmap <C-c><C-j> :NewQuickTemplateTab javascript<cr>
nmap <C-c><C-c> :NewQuickTemplateTab css<cr>

" 在文件名上按gf时,在新的tab中打开
map gf :tabnew <cfile><cr>


"jquery 配色
au BufRead,BufNewFile *.js set syntax=jquery

" jsLint for Vim
let g:jslint_highlight_color = '#996600'
" 指定 jsLint 调用路径,通常不用更改
let g:jslint_command = $HOME . '\/.vim\/jsl\/jsl'
" 指定 jsLint 的启动参数,可以指定相应的配置文件
let g:jslint_command_options = '-nofilelisting -nocontext -nosummary -nologo -process'


" 返回当前时间
func! GetTimeInfo()
"return strftime('%Y-%m-%d %A %H:%M:%S')
return strftime('%Y-%m-%d %H:%M:%S')
endfunction

" 插入模式按 Ctrl + D(ate) 插入当前时间
imap <C-d> <C-r>=GetTimeInfo()<cr>

" ==================
" plugin list
" ==================
"Color Scheme Explorer
"jsbeauty \ff
"NERDTree
"Calendar
"conquer_term
"nerd_commenter

"setup for C and C++
filetype plugin on
set nocp

详细使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
UILabel *label = [[UILabelalloc] initWithFrame:CGRectMake(0, 0, 75, 40)];   //声明UIlbel并指定其位置和长宽
label.backgroundColor = [UIColorclearColor]; //设置label的背景色,这里设置为透明色。
label.font = [UIFont fontWithName:@"Helvetica-Bold" size:13]; //设置label的字体和字体大小。
label.transform = CGAffineTransformMakeRotation(0.1); //设置label的旋转角度
label.text = @“helloworld”; //设置label所显示的文本
label.textColor = [UIColorwhiteColor]; //设置文本的颜色
label.shadowColor = [UIColorcolorWithWhite:0.1falpha:0.8f]; //设置文本的阴影色彩和透明度。
label.shadowOffset = CGSizeMake(2.0f, 2.0f); //设置阴影的倾斜角度。
label.textAlignment = UITextAlignmentCenter; //设置文本在label中显示的位置,这里为居中。
//换行技巧:如下换行可实现多行显示,但要求label有足够的宽度。
label.lineBreakMode = UILineBreakModeWordWrap; //指定换行模式
label.numberOfLines = 2; // 指定label的行数
//lable的旋转
label.transform = CGAffineTransformMakeRotation(0.2); //设置label的旋转角度
[self.view addSubview:label]; //将label载入

label的美化和特效:

这里使用FXLabel来实现特殊效果,如上图的“每日”二字就是用FXLabel来实现的,但要加入FXLbal.h和FXLabel.m两个文件,具体代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
FXLabel *label = [[FXLabelalloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
label.backgroundColor = [UIColorclearColor];
label.font = [UIFontfontWithName:@"Helvetica-Bold"size:15];
label.text = [secondTitle objectAtIndex:i];
label.textColor = [UIColorgrayColor];
label.shadowColor = [UIColorcolorWithWhite:1.0falpha:0.8f];
label.shadowOffset = CGSizeMake(1.0f, 2.0f);
label.shadowBlur = 1.0f;
label.innerShadowColor = [UIColorcolorWithWhite:0.0falpha:0.8f];
label.innerShadowOffset = CGSizeMake(1.0f, 2.0f);
label.textAlignment = UITextAlignmentLeft;
[view addSubview:label];

其用法和UILabel相差不大,很好理解,代码大家可以直接调用,具体属性自己修改。

FXLabel下面地址:https://github.com/nicklockwood/FXLabel

来源:http://wuchaorang.2008.blog.163.com/blog/static/48891852201232014339972/

要在屏幕上显示内容首先要创建一个窗口承载内容,要创建一个窗口,需要一个边框(frame),含有边框信息的底层 结构就CGRect。每个能够在屏幕上显示自己的对象都有一个边框,定义了他的显示区域,不过许多高层的视图类会自动计算这一信息。其他的那些类则在视图初始化时通过一个initWithFrame的初始化方法来设置。

再来认识一个类:UIScreen。UIScreen类代表了屏幕,通过这个类我们可以获取一些想要的东东。可使用下面的代码测试一下:

1
2
3
4
5
6
7
8
9
CGrect screenBounds = [ [UIScreen mainScreen]bounds];//返回的是带有状态栏的Rect  
CGRect viewBounds = [ [UIScreen mainScreen]applicationFrame];//不包含状态栏的Rect
//screenBounds 与 viewBounds 均是相对于设备屏幕来说的
//所以 screenBounds.origin.x== 0.0 ; screenBounds.oringin.y = 0.0;
screenBounds.size.width == 320;
screenBounds.size.height == 480(或者其他分辨率有所差异)
//所以 screenBounds.origin.x== 0.0 ; screenBounds.oringin.y = 20.0;(因为状态栏的高度是20像素)
screenBounds.size.width == 320;
screenBounds.size.height == 480

UIView

下面来认识一下UIView类,这个类继承自UIResponder,看这个名字我们就知道它是负责显示的画布,如果说把window比作画框的话。我们 就是不断地在画框上移除、更换或者叠加画布,或者在画布上叠加其他画布,大小当然 由绘画者来决定了。有了画布,我们就可以在上面任意施为了。这个类在UIView.h里面。

1
UIView* myView =[[ UIView alloc]initWithFrame:CGRectMake(0.0,0.0,200.0,400.0)];//这里创建了一块画布,定义了相对于父窗口的位置, 以及大小。

UIWindow

UIWindow继承自UIView,关于这一点可能有点逻辑障碍,画框怎么继承自画布呢?不要过于去专牛角尖,画框的形状不就是跟画布一样吗?拿一块画布然后用一些方法把它加强,是不是可以当一个画框用呢?这也是为什么 一个view可以直接加到另一个view上去的原因了。
看一下系统的初始化过程(在application didFinishLauchingWithOptions里面):

1
2
3
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];  
self.window.backgroundColor = [UIColor grayColor];//给window设置一个背景色
[self.window makeKeyAndVisible];//让window显示出来

实战演练一下:

1)新建一个工程选择Empty Application 名字为practice

2)在application didFinishLaunchingWithOptions里面,你会发现系统已经建好一个画框了,我们现在就用系统帮我们建好的画框,你当然也可以自己建一个画框,不过没这个必要了,忘了讲了,一个应用程序只能有一个画框。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.

CGRect bound = [[UIScreen mainScreen]bounds];
NSLog(@"boundwith:%f boundheight:%f",bound.size.width,bound.size.height);
NSLog(@"boundx:%f boundy:%f",bound.origin.x,bound.origin.y);

CGRect appBound = [[UIScreen mainScreen]applicationFrame];
NSLog(@"appBoundwith:%f boundheight:%f",appBound.size.width,appBound.size.height);
NSLog(@"appBoundx:%f boundy:%f",appBound.origin.x,appBound.origin.y);

//画第一块画布然涂成蓝色,大小是320 X 100
CGRect CGone = CGRectMake(0.0, 0.0, 320, 100);//画个矩形,初始化位置与大小
UIView *v_one = [[UIView alloc]initWithFrame:CGone];//初始化view
v_one.backgroundColor = [UIColor blueColor];// 涂成蓝色
[self.window addSubview:v_one];//直接加到画框上

//第二块注意它的位置
CGRect CGtwo = CGRectMake(0.0, 100, 160, 100);//画个矩形、初始化位置与大小
UIView *v_two = [[UIView alloc]initWithFrame:CGtwo];//初始化view
v_two.backgroundColor = [UIColor redColor];//涂成红色
[self.window addSubview:v_two];//叠加到画框
//第三块注意他的位置
CGRect CGthree = CGRectMake(160, 100, 160, 100);//
UIView *v_three = [[UIView alloc]initWithFrame:CGthree];//
v_three.backgroundColor = [UIColor greenColor];//
[self.window addSubview:v_three];//
//第四块注意它的位置
CGRect CGfour = CGRectMake(0.0, 260, 320, 200);//
UIView *v_four = [[UIView alloc]initWithFrame:CGfour];//
v_four.backgroundColor = [UIColor orangeColor];//
[self.window addSubview:v_four];//
//第五块,计算一下它的位置,看看它的效果,
//你可以让试一下把这段代码移到第一快初始化的上面试试,会有意想不到的效果
CGRect CGfive = CGRectMake(100, 150, 160, 200);
UIView *v_five = [[UIView alloc]initWithFrame:CGfive];
v_five.backgroundColor = [UIColor yellowColor];
[self.window addSubview:v_five];
self.window.backgroundColor = [UIColor grayColor];//
[self.window makeKeyAndVisible];//

//最后记得release
v_one = nil;
v_two = nil;
v_three = nil;
v_four = nil;
v_five = nil;

return YES;
//self.window.backgroundColor = [UIColor whiteColor];
//[self.window makeKeyAndVisible];
//return YES;
}

取得画面工作区域的大小

iOS 可以在很多 Apple 的装置上执行,然而每个装置所提供的工作区域大小 Application Frame 也不尽香同,下面提供一个简单的方法,帮助你可以快速找出目前工作区域的画面的大小,程式码如下。

1,首先是状态列 Status Bar 的部份。

1
2
3
4
//取得StatusBar的位置和大小
[self.view addSubview:theToolbar];
CGRect statusBarRect = [[UIApplication sharedApplication]statusBarFrame];
NSLog(@\"%@\", NSStringFromCGRect(statusBarRect));

2,再来是可工作区域的大小,如果你的应用程式包含状态列,那么可工作区域的大小就会是整个画面的减去状态列所剩下的区域。

1
2
3
//取得工作区域的位置和大小
CGRect workSpaceRect = [[UIScreen mainScreen]applicationFrame];
NSLog(@\"%@\", NSStringFromCGRect(workSpaceRect));

3,最后就是整个画面的大小

1
2
3
//取得整个画面的位置和大小
CGRect windowRect = [[UIScreen mainScreen]bounds];
NSLog(@\"%@\", NSStringFromCGRect(windowRect));

上述程式码皆是将取得的大小范围资讯储存在 CGRect 型态的变数中,再将此变数以字串的方式显示出来。

一些 UIView 中管理 Subview 常用的方法

一个 UIView 里面可以包含许多的 Subview(其他的 UIView),而这些 Subview 彼此之间是有所谓的阶层关系,这有点类似绘图软体中图层的概念,下面程式码示演示了几个在管理图层(Subview)上常用的方法,其程式码如下。
首先是大家最常使用的新增和移除 Subview。

1
2
3
4
//将Subview从当前的UIView中移除
[Subview removeFromSuperview];
//替UIView增加一个Subview
[UIView addSubview:Subview];

在 UIView 中将 Subview 往前或是往后移动一个图层,往前移动会覆盖住较后层的 Subview,而往后移动则会被较上层的 Subview 所覆盖。

1
2
3
4
//将Subview往前移动一个图层(与它的前一个图层对调位置)
[UIView bringSubviewToFront:Subview];
//将Subview往后移动一个图层(与它的后一个图层对调位置)
[UIView sendSubviewToBack:Subview];

在 UIView 中使用索引 Index 交换两的 Subview 彼此的图层层级。

1
2
//交换两个图层
[UIView exchangeSubviewAtIndex:indexA withSubviewAtIndex:indexB];

使用 Subview 的变数名称取得它在 UIView 中的索引值(Index )。

1
2
//取得Index
NSInteger index = [[UIView subviews] indexOfObject:Subview名称];

替 Subview 加上 NSInteger 的註记 (Tag),好让之后它们分辨彼此

1
2
//加上註记
[Subview setTag:NSInteger];

最后是取得 UIView 中所有的 Subview,呼叫此方法会传回一个 NSArray,并以由后往前的顺序列出这些 Subview,下图中是列出范例图片里 Root 中所有的 Subview。

1
2
//取的UIView下的所有Subview
[UIView subviews]

代码:

1
2
3
4
5
6
7
8
CG_INLINE CGRect  
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x; rect.origin.y = y;
rect.size.width = width; rect.size.height = height;
return rect;
}

这个方法就是make一个rect,定好origin(起点,左上角),宽与高,就可以画出一个位置与大小确定的rect(矩形)这个函数被声明为内联函 数,一是因为它比较小,二是因为在画界面时我们要求一定的效率。这个函数还是藏在刚刚那个头文件里面:CGGeometry.h

三个结构体:CGPoint、CGSize、CGRect

  1. CGPoint
1
2
3
4
5
6
/* Points. */    
struct CGPoint {
CGFloat x;
CGFloat y;
};
typedef struct CGPoint CGPoint;
  1. CGSize
1
2
3
4
5
6
/* Sizes. */    
struct CGSize {
CGFloat width;
CGFloat height;
};
typedef struct CGSize CGSize;

3.CGRect

1
2
3
4
5
6
/* Rectangles. */    
struct CGRect {
CGPoint origin;//偏移是相对父窗口的
CGSize size;
};
typedef struct CGRect CGRect;

这三个结构体均在一个头文件里:CGGeometry.h

使用之前请从Apple网站下载示例:点此下载

然后将Reachability.h 和 Reachability.m 加到自己的项目中,并引用 SystemConfiguration.framework,就可以使用了。

Reachability 中定义了3种网络状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
// the network state of the device for Reachability 1.5.
typedef enum {
NotReachable = 0, //无连接
ReachableViaCarrierDataNetwork, //使用3G/GPRS网络
ReachableViaWiFiNetwork //使用WiFi网络
} NetworkStatus;

// the network state of the device for Reachability 2.0.
typedef enum {
NotReachable = 0, //无连接
ReachableViaWiFi, //使用3G/GPRS网络
ReachableViaWWAN //使用WiFi网络
} NetworkStatus;

比如检测某一特定站点的接续状况,可以使用下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
Reachability *r = [Reachability reachabilityWithHostName:@“www.apple.com”];
switch ([r currentReachabilityStatus]) {
case NotReachable:
// 没有网络连接
break;
case ReachableViaWWAN:
// 使用3G网络
break;
case ReachableViaWiFi:
// 使用WiFi网络
break;
}

检测当前网络环境:

1
2
3
4
5
6
7
8
9
// 是否wifi
+ (BOOL) IsEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

// 是否3G
+ (BOOL) IsEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}

连接状态实时通知

网络连接状态的实时检查,通知在网络应用中也是十分必要的。接续状态发生变化时,需要及时地通知用户。由于Reachability1.5版与2.0版有一些变化,这里分开来说明使用方法。

Reachability 1.5

My.AppDelegate.h
1
2
3
4
5
6
7
8
9
#import "Reachability.h"

@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
NetworkStatus remoteHostStatus;
}

@property NetworkStatus remoteHostStatus;

@end
My.AppDelegate.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#import "MyAppDelegate.h"

@implementation MyAppDelegate

@synthesize remoteHostStatus;

// 更新网络状态
- (void)updateStatus {
self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
}

// 通知网络状态
- (void)reachabilityChanged:(NSNotification *)note {
[self updateStatus];
if (self.remoteHostStatus == NotReachable) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"AppName", nil) message:NSLocalizedString(@"NotReachable", nil)
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
}

// 程序启动器,启动网络监视
- (void)applicationDidFinishLaunching:(UIApplication *)application {

// 设置网络检测的站点
[[Reachability sharedReachability] setHostName:@"www.apple.com"];
[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
// 设置网络状态变化时的通知函数
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)
name:@"kNetworkReachabilityChangedNotification" object:nil];
[self updateStatus];
}

- (void)dealloc {
// 删除通知对象
[[NSNotificationCenter defaultCenter] removeObserver:self];
[window release];
[super dealloc];
}

Reachability 2.0

MyAppDelegate.h
1
2
3
4
5
6
7
@class Reachability;

@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
Reachability *hostReach;
}

@end
MyAppDelegate.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
25
26
27
- (void)reachabilityChanged:(NSNotification *)note {
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
NetworkStatus status = [curReach currentReachabilityStatus];

if (status == NotReachable) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AppName"
message:@"NotReachable"
delegate:nil
cancelButtonTitle:@"YES" otherButtonTitles:nil];
[alert show];
[alert release];
}
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// ...

// 监测网络情况
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];
hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];
[hostReach startNotifer];
// ...
}

来源:http://www.cnblogs.com/mrhgw/archive/2012/08/01/2617760.html

最近在搞数据展示,需要将数据用图表展示出来,结果还是没有达到自己理想的效果,先将自己的不完美版本,记录一下,直接贴出代码

detailViewController.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
@interface DetailsViewController : UIViewController<CPTPlotDataSource, CPTAxisDelegate>
{
CPTXYGraph *graph; //画板
CPTScatterPlot *dataSourceLinePlot;//线
NSMutableArray *dataForPlot1; //坐标数组
NSTimer *timer1; //定时器
int j;
int r;
int maxX;
int maxY;
int minX;
int minY;
}
@property (retain, nonatomic) NSMutableArray *dataForPlot1;
@property (strong, nonatomic) NSString *value;
@property (strong, nonatomic) NSString *key;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) CPTXYGraph *graph;
@property (strong, nonatomic) NSMutableArray *points;
@property (strong, nonatomic) NSMutableArray *xArr;
@property (strong, nonatomic) NSMutableArray *yArr;
//折线图
-(void) lineChart;
//填充图
-(void) fillFigure;
@end

detailViewController.h(里面有两个函数,是分别调用折线图和填充图的)

detailViewController.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#import "DetailsViewController.h"

@interface DetailsViewController ()

@end

@implementation DetailsViewController

@synthesize value;
@synthesize key;
@synthesize dataForPlot1;
@synthesize graph;
@synthesize points;

@synthesize yArr;
@synthesize xArr;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
//构造数据
self.points = [[NSMutableArray alloc] init];
NSUInteger i;
self.xArr = [[NSMutableArray alloc] init];
self.yArr = [[NSMutableArray alloc] init];

for(i=0;i<60;i++){
id x = [NSNumber numberWithFloat: 1+i*0.5];
id y = [NSNumber numberWithFloat: 1.2 * rand()/(float)RAND_MAX+1.2];

[self.xArr addObject:x];
[self.yArr addObject:y];
[self.points addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x,@"x",y,@"y", nil]];
NSNumber *tmpX = [NSNumber numberWithFloat:[x intValue]];
NSNumber *tmpY = [NSNumber numberWithFloat:[y intValue]];

maxX = MAX([tmpX intValue], maxX);
minX = MIN([tmpX intValue], minX);
maxY = MAX([tmpY intValue], maxY);
minY = MIN([tmpY intValue], minY);
}
NSLog(@"maxX = %d",maxX);
NSLog(@"minX = %d",minX);
NSLog(@"maxY = %d",maxY);
NSLog(@"minY = %d",minY);
// NSLog(@"xArr = %@",self.xArr);
// NSLog(@"yArr = %@",self.yArr);

}
return self;
}

- (void)viewDidLoad{
[super viewDidLoad];
self.title = self.value;
[self lineChart];


}

//GridLine
-(void) gridLine{

}

//折线图
-(void) lineChart{
graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
[graph applyTheme:theme];
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds];

//设置图表的边框
//左边的padding设置为0
graph.paddingLeft = 0;
//顶部的的padding设置0
graph.paddingTop = 0;
//右边的padding设置为0
graph.paddingRight = 0;
//底部的padding设置为0
graph.paddingBottom = 0;

//坐标区域的边框设置
//左边的padding设置为45.0
graph.plotAreaFrame.paddingLeft = 40.0 ;
//顶部的padding设置为40.0
graph.plotAreaFrame.paddingTop = 10.0 ;
//右边的padding设置为5.0
graph.plotAreaFrame.paddingRight = 10.0 ;
//底部的padding设置为80.0
graph.plotAreaFrame.paddingBottom = 10.0 ;


hostingView.hostedGraph = graph;

//定义绘图空间
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = NO;
//设置x,y坐标范围
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(minX) length:CPTDecimalFromFloat(maxX)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(minY) length:CPTDecimalFromFloat(maxY+2)];

//散点图的绘制
CPTScatterPlot *boundLinePlot = [[CPTScatterPlot alloc] init];
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.miterLimit = 1.0f;
lineStyle.lineWidth = 3.0f;
lineStyle.lineColor = [CPTColor blueColor];

boundLinePlot.dataLineStyle = lineStyle;
boundLinePlot.identifier = @"lineChart";
boundLinePlot.dataSource = self;
[graph addPlot:boundLinePlot];

//设置坐标轴
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) graph.axisSet;

CPTXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPTDecimalFromString(@"10");
x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
x.minorTicksPerInterval = 10;
// NSArray *xexclusionRanges = [NSArray arrayWithObjects:
// [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(1.99) length:CPTDecimalFromFloat(0.02)],
// [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.99) length:CPTDecimalFromFloat(0.02)],
// [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(2.99) length:CPTDecimalFromFloat(0.02)], nil];
// x.labelExclusionRanges = xexclusionRanges;

CPTXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPTDecimalFromString(@"1");
y.orthogonalCoordinateDecimal = CPTDecimalFromString(@"1");
y.minorTicksPerInterval = 1;




[self.view addSubview:hostingView];

}

//填充图
-(void) fillFigure{
//创建图表
graph = [[CPTXYGraph alloc] initWithFrame:self.view.bounds];

//给图表添加一个主题
CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
[graph applyTheme:theme];

//创建画板,将图表添加到画板
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
hostingView.hostedGraph = graph;
[self.view addSubview:hostingView];

//设置图表的边框
//左边的padding设置为0
graph.paddingLeft = 0;
//顶部的的padding设置0
graph.paddingTop = 0;
//右边的padding设置为0
graph.paddingRight = 0;
//底部的padding设置为0
graph.paddingBottom = 0;

//坐标区域的边框设置
//左边的padding设置为45.0
graph.plotAreaFrame.paddingLeft = 40.0 ;
//顶部的padding设置为40.0
graph.plotAreaFrame.paddingTop = 40.0 ;
//右边的padding设置为5.0
graph.plotAreaFrame.paddingRight = 15.0 ;
//底部的padding设置为80.0
graph.plotAreaFrame.paddingBottom = 80.0 ;


//设置坐标范围
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
// plotSpace.xRange = [CPTPlotRange ];
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(200.0)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(200.0)];

//设置坐标刻度大小
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) graph.axisSet ;
CPTXYAxis *x = axisSet.xAxis ;
//x 轴:不显示小刻度线
x. minorTickLineStyle = nil ;
// 大刻度线间距: 50 单位
x. majorIntervalLength = CPTDecimalFromString (@"50");
// 坐标原点: 0
x. orthogonalCoordinateDecimal = CPTDecimalFromString ( @"0" );

CPTXYAxis *y = axisSet.yAxis ;
//y 轴:不显示小刻度线
y. minorTickLineStyle = nil ;
// 大刻度线间距: 50 单位
y. majorIntervalLength = CPTDecimalFromString ( @"50" );
// 坐标原点: 0
y. orthogonalCoordinateDecimal = CPTDecimalFromString (@"0");

//创建绿色区域
dataSourceLinePlot = [[CPTScatterPlot alloc] init];
dataSourceLinePlot.identifier = @"Green Plot";

//设置绿色区域边框的样式
CPTMutableLineStyle *lineStyle = [dataSourceLinePlot.dataLineStyle mutableCopy];
//设置线的宽度
lineStyle.lineWidth = 1.f;
//设置线的颜色
lineStyle.lineColor = [CPTColor greenColor];
//添加线到绿色区域中
dataSourceLinePlot.dataLineStyle = lineStyle;
//设置透明实现添加动画
dataSourceLinePlot.opacity = 0.0f;

//设置数据元代理
dataSourceLinePlot.dataSource = self;
//绿色区域添加到图表中
[graph addPlot:dataSourceLinePlot];

// 创建一个颜色渐变:从 建变色 1 渐变到 无色
CPTGradient *areaGradient = [ CPTGradient gradientWithBeginningColor :[CPTColor greenColor] endingColor :[CPTColor colorWithComponentRed:0.65 green:0.65 blue:0.16 alpha:0.2]];
// 渐变角度: -90 度(顺时针旋转)
areaGradient.angle = -90.0f ;
// 创建一个颜色填充:以颜色渐变进行填充
CPTFill *areaGradientFill = [ CPTFill fillWithGradient :areaGradient];
// 为图形设置渐变区
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPTDecimalFromString ( @"0.0" );
dataSourceLinePlot.interpolation = CPTScatterPlotInterpolationLinear ;


dataForPlot1 = [[NSMutableArray alloc] init];
// j = 200;
// r = 0;
// timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dataOpt) userInfo:nil repeats:YES];
// [timer1 fire];
[self plotData];
}

//添加数据
-(void) plotData{
if ([dataSourceLinePlot.identifier isEqual:@"Green Plot"]) {
NSString *xp1 = [NSString stringWithFormat:@"%d",1];
NSString *yp1 = [NSString stringWithFormat:@"%d",10];
NSMutableDictionary *point1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp1, @"x", yp1, @"y", nil];
[dataForPlot1 insertObject:point1 atIndex:0];

NSString *xp2 = [NSString stringWithFormat:@"%d",10];
NSString *yp2 = [NSString stringWithFormat:@"%d",25];
NSMutableDictionary *point2 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp2, @"x", yp2, @"y", nil];
[dataForPlot1 insertObject:point2 atIndex:1];

NSString *xp3 = [NSString stringWithFormat:@"%d",30];
NSString *yp3 = [NSString stringWithFormat:@"%d",15];
NSMutableDictionary *point3 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp3, @"x", yp3, @"y", nil];
[dataForPlot1 insertObject:point3 atIndex:2];

NSString *xp4 = [NSString stringWithFormat:@"%d",50];
NSString *yp4 = [NSString stringWithFormat:@"%d",80];
NSMutableDictionary *point4 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp4, @"x", yp4, @"y", nil];
[dataForPlot1 insertObject:point4 atIndex:3];

NSString *xp5 = [NSString stringWithFormat:@"%d",70];
NSString *yp5 = [NSString stringWithFormat:@"%d",60];
NSMutableDictionary *point5 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp5, @"x", yp5, @"y", nil];
[dataForPlot1 insertObject:point5 atIndex:4];

NSString *xp6 = [NSString stringWithFormat:@"%d",90];
NSString *yp6 = [NSString stringWithFormat:@"%d",100];
NSMutableDictionary *point6 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp6, @"x", yp6, @"y", nil];
[dataForPlot1 insertObject:point6 atIndex:5];

NSString *xp7 = [NSString stringWithFormat:@"%d",110];
NSString *yp7 = [NSString stringWithFormat:@"%d",70];
NSMutableDictionary *point7 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp7, @"x", yp7, @"y", nil];
[dataForPlot1 insertObject:point7 atIndex:6];

NSString *xp8 = [NSString stringWithFormat:@"%d",130];
NSString *yp8 = [NSString stringWithFormat:@"%d",80];
NSMutableDictionary *point8 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp8, @"x", yp8, @"y", nil];
[dataForPlot1 insertObject:point8 atIndex:7];

NSString *xp9 = [NSString stringWithFormat:@"%d",200];
NSString *yp9 = [NSString stringWithFormat:@"%d",135];
NSMutableDictionary *point9 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp9, @"x", yp9, @"y", nil];
[dataForPlot1 insertObject:point9 atIndex:8];
}
}
//使用CorePlot的委托方法 呈现图形 - lineChart
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
return [self.points count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSString *key = (fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y");
NSNumber *num = [[self.points objectAtIndex:index] valueForKey:key];
return num;
}


//使用CorePlot的委托方法 呈现图形 - fillFigure
//-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
// return [dataForPlot1 count];
//}
//
//-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
// NSNumber *num;
// //让视图偏移
// if ( [(NSString *)plot.identifier isEqualToString:@"Green Plot"] ) {
// NSString *key = (fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y");
//
// num = [[dataForPlot1 objectAtIndex:index] valueForKey:key];
// if ( fieldEnum == CPTScatterPlotFieldX ) {
// num = [NSNumber numberWithDouble:[num doubleValue] - r];
// }
// }
// //添加动画效果
// CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
// fadeInAnimation.duration = 1.0f;
// fadeInAnimation.removedOnCompletion = NO;
// fadeInAnimation.fillMode = kCAFillModeForwards;
// fadeInAnimation.toValue = [NSNumber numberWithFloat:2.0];
// [dataSourceLinePlot addAnimation:fadeInAnimation forKey:@"animateOpacity"];
// return num;
//}


- (void) dataOpt{
//添加随机数
if ([dataSourceLinePlot.identifier isEqual:@"Green Plot"]) {
NSString *xp = [NSString stringWithFormat:@"%d",j];
NSString *yp = [NSString stringWithFormat:@"%d",(rand()%100)];
NSMutableDictionary *point1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp, @"x", yp, @"y", nil];
[dataForPlot1 insertObject:point1 atIndex:0];
}
//刷新画板
[graph reloadData];
j = j + 20;
r = r + 20;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{

return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

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

@end
0%