余一

纸上得来终觉浅,绝知此事要躬行。

0%

Android动画

Android的动画分为三大类:帧动画补间动画属性动画

帧动画

​ 帧动画是实现原理最简单的一种,跟现实生活中的电影胶卷类似,都是在短时间内连续播放多张图片,从而模拟动态画面的效果。

帧动画的实现

通过代码实现

​ 帧动画由动画图形AnimationDrawable生成。下面是AnimationDrawable的常用方法:

  • addFrame:添加一幅图片帧,并指定该帧的持续时间(单位毫秒)。
  • setOneShot:设置是否只播放一次。为true表示只播放一次,为false表示循环播放。
  • start:开始播放。注意,设置宿主视图后才能进行播放。
  • stop:停止播放。
  • isRunning:判断是否正在播放。

​ 有了动画图形,还得有一个宿主视图显示该图形,一般使用图像视图ImageView承载AnimationDrawable,即调用ImageView对象的setImageDrawable方法将动画图形加载到图像视图中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 代码方式显示帧动画
*/
@SuppressLint("UseCompatLoadingForDrawables")
fun showFrameAnimByCode(){
//帧动画需要把每帧图片加入AnimationDrawable队列
animationDrawable.apply {
//添加一幅图片帧,并指定该帧的持续时间(单位毫秒)。
addFrame(resources.getDrawable(R.drawable.flow_p1,this@FrameAnimActivity.theme),50)
addFrame(resources.getDrawable(R.drawable.flow_p2,this@FrameAnimActivity.theme),50)
addFrame(resources.getDrawable(R.drawable.flow_p3,this@FrameAnimActivity.theme),50)
addFrame(resources.getDrawable(R.drawable.flow_p4,this@FrameAnimActivity.theme),50)
addFrame(resources.getDrawable(R.drawable.flow_p5,this@FrameAnimActivity.theme),50)
addFrame(resources.getDrawable(R.drawable.flow_p6,this@FrameAnimActivity.theme),50)
addFrame(resources.getDrawable(R.drawable.flow_p7,this@FrameAnimActivity.theme),50)
addFrame(resources.getDrawable(R.drawable.flow_p8,this@FrameAnimActivity.theme),50)
//setOneShot为true表示只播放一次,为false表示循环播放
isOneShot = false
mBinding.ivFrameAnim.setImageDrawable(this)
start()
}
}

通过xml方式实现

​ 先把帧图片的排列定义在一个XML文件中;然后在代码中直接调用ImageView对象的setImageResource方法,加载帧动画的图形定义文件;再调用ImageView对象的getDrawable方法,获得动画图形的实例,并进行后续的播放操作。

如:定义drawable文件,frame_anim.xml:

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
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item
android:drawable="@drawable/flow_p1"
android:duration="50" />
<item
android:drawable="@drawable/flow_p2"
android:duration="50" />
<item
android:drawable="@drawable/flow_p3"
android:duration="50" />
<item
android:drawable="@drawable/flow_p4"
android:duration="50" />
<item
android:drawable="@drawable/flow_p5"
android:duration="50" />
<item
android:drawable="@drawable/flow_p6"
android:duration="50" />
<item
android:drawable="@drawable/flow_p7"
android:duration="50" />
<item
android:drawable="@drawable/flow_p8"
android:duration="50" />
</animation-list>

在Activity中创建方法调用:

1
2
3
4
5
6
7
8
/**
* xml方式启动帧动画
*/
fun showFrameAnimByXml(){
mBinding.ivFrameAnim.setImageResource(R.drawable.frame_anim)
animationDrawable = mBinding.ivFrameAnim.drawable as AnimationDrawable
animationDrawable.start()
}

显示GIF动画

​ Android虽然号称支持PNG、JPG、GIF三种图片格式,但是并不支持直接播放GIF动图,如果在图像视图中加载一张GIF文件,只会显示GIF文件的第一帧图片。

借助帧动画播放拆解后的组图

​ 将GIF文件分解为一系列图片数据,并获取每帧的持续时间,然后通过动画图形动态加载每帧图片。

从GIF文件中分解帧图片有现成的开源代码:

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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package com.study.animationstudy.util;

import java.io.InputStream;
import java.util.Vector;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

//Handler for read & extract Bitmap from *.gif
public class GifImage {

// to store *.gif data, Bitmap & delay
public static class GifFrame {
// to access image & delay w/o interface
public Bitmap image;
public int delay;

public GifFrame(Bitmap im, int del) {
image = im;
delay = del;
}

}

// to define some error type
public static final int STATUS_OK = 0;
public static final int STATUS_FORMAT_ERROR = 1;
public static final int STATUS_OPEN_ERROR = 2;

protected int status;
protected InputStream in;

protected int width; // full image width
protected int height; // full image height
protected boolean gctFlag; // global color table used
protected int gctSize; // size of global color table
protected int loopCount = 1; // iterations; 0 = repeat forever

protected int[] gct; // global color table
protected int[] lct; // local color table
protected int[] act; // active color table

protected int bgIndex; // background color index
protected int bgColor; // background color
protected int lastBgColor; // previous bg color
protected int pixelAspect; // pixel aspect ratio

protected boolean lctFlag; // local color table flag
protected boolean interlace; // interlace flag
protected int lctSize; // local color table size

protected int ix, iy, iw, ih; // current image rectangle
protected int lrx, lry, lrw, lrh;
protected Bitmap image; // current frame
protected Bitmap lastImage; // previous frame
protected int frameindex = 0;

public int getFrameindex() {
return frameindex;
}

public void setFrameindex(int frameindex) {
this.frameindex = frameindex;
if (frameindex > frames.size() - 1) {
frameindex = 0;
}
}

protected byte[] block = new byte[256]; // current data block
protected int blockSize = 0; // block size

// last graphic control extension info
protected int dispose = 0;
// 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
protected int lastDispose = 0;
protected boolean transparency = false; // use transparent color
protected int delay = 0; // delay in milliseconds
protected int transIndex; // transparent color index

protected static final int MaxStackSize = 4096;
// max decoder pixel stack size

// LZW decoder working arrays
protected short[] prefix;
protected byte[] suffix;
protected byte[] pixelStack;
protected byte[] pixels;

protected Vector<GifFrame> frames; // frames read from current file
protected int frameCount;

// to get its Width / Height
public int getWidth() {
return width;
}

public int getHeigh() {
return height;
}

/**
* Gets display duration for specified frame.
*
* @param n
* int index of frame
* @return delay in milliseconds
*/
public int getDelay(int n) {
delay = -1;
if ((n >= 0) && (n < frameCount)) {
delay = ((GifFrame) frames.elementAt(n)).delay;
}
return delay;
}

public int getFrameCount() {
return frameCount;
}

public Bitmap getImage() {
return getFrame(0);
}

public int getLoopCount() {
return loopCount;
}

protected void setPixels() {
int[] dest = new int[width * height];
// fill in starting image contents based on last image's dispose code
if (lastDispose > 0) {
if (lastDispose == 3) {
// use image before last
int n = frameCount - 2;
if (n > 0) {
lastImage = getFrame(n - 1);
} else {
lastImage = null;
}
}
if (lastImage != null) {
lastImage.getPixels(dest, 0, width, 0, 0, width, height);
// copy pixels
if (lastDispose == 2) {
// fill last image rect area with background color
int c = 0;
if (!transparency) {
c = lastBgColor;
}
for (int i = 0; i < lrh; i++) {
int n1 = (lry + i) * width + lrx;
int n2 = n1 + lrw;
for (int k = n1; k < n2; k++) {
dest[k] = c;
}
}
}
}
}

// copy each source line to the appropriate place in the destination
int pass = 1;
int inc = 8;
int iline = 0;
for (int i = 0; i < ih; i++) {
int line = i;
if (interlace) {
if (iline >= ih) {
pass++;
switch (pass) {
case 2:
iline = 4;
break;
case 3:
iline = 2;
inc = 4;
break;
case 4:
iline = 1;
inc = 2;
}
}
line = iline;
iline += inc;
}
line += iy;
if (line < height) {
int k = line * width;
int dx = k + ix; // start of line in dest
int dlim = dx + iw; // end of dest line
if ((k + width) < dlim) {
dlim = k + width; // past dest edge
}
int sx = i * iw; // start of line in source
while (dx < dlim) {
// map color and insert in destination
int index = ((int) pixels[sx++]) & 0xff;
int c = act[index];
if (c != 0) {
dest[dx] = c;
}
dx++;
}
}
}
image = Bitmap.createBitmap(dest, width, height, Config.RGB_565);
}

public Bitmap getFrame(int n) {
Bitmap im = null;
if ((n >= 0) && (n < frameCount)) {
im = ((GifFrame) frames.elementAt(n)).image;
}
return im;
}

public GifFrame[] getFrames() {
if (null != frames)
return frames.toArray(new GifFrame[0]);
return null;
}

public Bitmap nextBitmap() {
frameindex++;
if (frameindex > frames.size() - 1) {
frameindex = 0;
}
return ((GifFrame) frames.elementAt(frameindex)).image;
}

public int nextDelay() {
return ((GifFrame) frames.elementAt(frameindex)).delay;
}

// to read & parse all *.gif stream
public int read(InputStream is) {
init();
if (is != null) {
in = is;
readHeader();
if (!err()) {
readContents();
if (frameCount < 0) {
status = STATUS_FORMAT_ERROR;
}
}
} else {
status = STATUS_OPEN_ERROR;
}
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return status;
}

protected void decodeImageData() {
int NullCode = -1;
int npix = iw * ih;
int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;

if ((pixels == null) || (pixels.length < npix)) {
pixels = new byte[npix]; // allocate new pixel array
}
if (prefix == null) {
prefix = new short[MaxStackSize];
}
if (suffix == null) {
suffix = new byte[MaxStackSize];
}
if (pixelStack == null) {
pixelStack = new byte[MaxStackSize + 1];
}
// Initialize GIF data stream decoder.
data_size = read();
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = NullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++) {
prefix[code] = 0;
suffix[code] = (byte) code;
}

// Decode GIF pixel stream.
datum = bits = count = first = top = pi = bi = 0;
for (i = 0; i < npix;) {
if (top == 0) {
if (bits < code_size) {
// Load bytes until there are enough bits for a code.
if (count == 0) {
// Read a new data block.
count = readBlock();
if (count <= 0) {
break;
}
bi = 0;
}
datum += (((int) block[bi]) & 0xff) << bits;
bits += 8;
bi++;
count--;
continue;
}
// Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size;

// Interpret the code
if ((code > available) || (code == end_of_information)) {
break;
}
if (code == clear) {
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = NullCode;
continue;
}
if (old_code == NullCode) {
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
}
in_code = code;
if (code == available) {
pixelStack[top++] = (byte) first;
code = old_code;
}
while (code > clear) {
pixelStack[top++] = suffix[code];
code = prefix[code];
}
first = ((int) suffix[code]) & 0xff;
// Add a new string to the string table,
if (available >= MaxStackSize) {
break;
}
pixelStack[top++] = (byte) first;
prefix[available] = (short) old_code;
suffix[available] = (byte) first;
available++;
if (((available & code_mask) == 0)
&& (available < MaxStackSize)) {
code_size++;
code_mask += available;
}
old_code = in_code;
}

// Pop a pixel off the pixel stack.
top--;
pixels[pi++] = pixelStack[top];
i++;
}
for (i = pi; i < npix; i++) {
pixels[i] = 0; // clear missing pixels
}
}

protected boolean err() {
return status != STATUS_OK;
}

// to initia variable
protected void init() {
status = STATUS_OK;
frameCount = 0;
frames = new Vector<GifFrame>();
gct = null;
lct = null;
}

protected int read() {
int curByte = 0;
try {
curByte = in.read();
} catch (Exception e) {
status = STATUS_FORMAT_ERROR;
}
return curByte;
}

protected int readBlock() {
blockSize = read();
int n = 0;
if (blockSize > 0) {
try {
int count = 0;
while (n < blockSize) {
count = in.read(block, n, blockSize - n);
if (count == -1) {
break;
}
n += count;
}
} catch (Exception e) {
e.printStackTrace();
}
if (n < blockSize) {
status = STATUS_FORMAT_ERROR;
}
}
return n;
}

// Global Color Table
protected int[] readColorTable(int ncolors) {
int nbytes = 3 * ncolors;
int[] tab = null;
byte[] c = new byte[nbytes];
int n = 0;
try {
n = in.read(c);
} catch (Exception e) {
e.printStackTrace();
}
if (n < nbytes) {
status = STATUS_FORMAT_ERROR;
} else {
tab = new int[256]; // max size to avoid bounds checks
int i = 0;
int j = 0;
while (i < ncolors) {
int r = ((int) c[j++]) & 0xff;
int g = ((int) c[j++]) & 0xff;
int b = ((int) c[j++]) & 0xff;
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
}
}
return tab;
}

// Image Descriptor
protected void readContents() {
// read GIF file content blocks
boolean done = false;
while (!(done || err())) {
int code = read();
switch (code) {
case 0x2C: // image separator
readImage();
break;
case 0x21: // extension
code = read();
switch (code) {
case 0xf9: // graphics control extension
readGraphicControlExt();
break;

case 0xff: // application extension
readBlock();
String app = "";
for (int i = 0; i < 11; i++) {
app += (char) block[i];
}
if (app.equals("NETSCAPE2.0")) {
readNetscapeExt();
} else {
skip(); // don't care
}
break;
default: // uninteresting extension
skip();
}
break;

case 0x3b: // terminator
done = true;
break;

case 0x00: // bad byte, but keep going and see what happens
break;
default:
status = STATUS_FORMAT_ERROR;
}
}
}

protected void readGraphicControlExt() {
read(); // block size
int packed = read(); // packed fields
dispose = (packed & 0x1c) >> 2; // disposal method
if (dispose == 0) {
dispose = 1; // elect to keep old image if discretionary
}
transparency = (packed & 1) != 0;
delay = readShort() * 10; // delay in milliseconds
transIndex = read(); // transparent color index
read(); // block terminator
}

// to get Stream - Head
protected void readHeader() {
String id = "";
for (int i = 0; i < 6; i++) {
id += (char) read();
}
if (!id.toUpperCase().startsWith("GIF")) {
status = STATUS_FORMAT_ERROR;
return;
}
readLSD();
if (gctFlag && !err()) {
gct = readColorTable(gctSize);
bgColor = gct[bgIndex];
}
}

protected void readImage() {
// offset of X
ix = readShort(); // (sub)image position & size
// offset of Y
iy = readShort();
// width of bitmap
iw = readShort();
// height of bitmap
ih = readShort();

// Local Color Table Flag
int packed = read();
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag

// Interlace Flag, to array with interwoven if ENABLE, with order
// otherwise
interlace = (packed & 0x40) != 0; // 2 - interlace flag
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7); // 6-8 - local color table size
if (lctFlag) {
lct = readColorTable(lctSize); // read table
act = lct; // make local table active
} else {
act = gct; // make global table active
if (bgIndex == transIndex) {
bgColor = 0;
}
}
int save = 0;
if (transparency) {
save = act[transIndex];
act[transIndex] = 0; // set transparent color if specified
}
if (act == null) {
status = STATUS_FORMAT_ERROR; // no color table defined
}
if (err()) {
return;
}
decodeImageData(); // decode pixel data
skip();
if (err()) {
return;
}
frameCount++;
// create new image to receive frame data
image = Bitmap.createBitmap(width, height, Config.RGB_565);
// createImage(width, height);
setPixels(); // transfer pixel data to image
frames.addElement(new GifFrame(image, delay)); // add image to frame
// list
if (transparency) {
act[transIndex] = save;
}
resetFrame();
}

// Logical Screen Descriptor
protected void readLSD() {
// logical screen size
width = readShort();
height = readShort();
// packed fields
int packed = read();
gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
// 2-4 : color resolution
// 5 : gct sort flag
gctSize = 2 << (packed & 7); // 6-8 : gct size
bgIndex = read(); // background color index
pixelAspect = read(); // pixel aspect ratio
}

protected void readNetscapeExt() {
do {
readBlock();
if (block[0] == 1) {
// loop count sub-block
int b1 = ((int) block[1]) & 0xff;
int b2 = ((int) block[2]) & 0xff;
loopCount = (b2 << 8) | b1;
}
} while ((blockSize > 0) && !err());
}

// read 8 bit data
protected int readShort() {
// read 16-bit value, LSB first
return read() | (read() << 8);
}

protected void resetFrame() {
lastDispose = dispose;
lrx = ix;
lry = iy;
lrw = iw;
lrh = ih;
lastImage = image;
lastBgColor = bgColor;
dispose = 0;
transparency = false;
delay = 0;
lct = null;
}

/**
* Skips variable length blocks up to and including next zero length block.
*/
protected void skip() {
do {
readBlock();
} while ((blockSize > 0) && !err());
}
}

显示gif的示例代码:

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
/**
* 借助于帧动画技术显示gif
* 将GIF文件分解为一系列图片数据,并获取每帧的持续时间,然后通过动画图形动态加载每帧图片。
*/
fun showGifAnim(){
val inputStream = resources.openRawResource(R.raw.welcome)
val gifImage = GifImage()
when(val code = gifImage.read(inputStream)){
GifImage.STATUS_OK -> {
//
val frameList = gifImage.frames
val animationDrawable = AnimationDrawable()
frameList.forEach {
//BitmapDrawable用于把Bitmap格式转换为Drawable格式
val bitmapDrawable = BitmapDrawable(resources,it.image)
animationDrawable.addFrame(bitmapDrawable,it.delay)
}
//循环播放
animationDrawable.isOneShot = false
mBinding.ivGif.setImageDrawable(animationDrawable)
animationDrawable.start()
}
GifImage.STATUS_FORMAT_ERROR -> {
Toast.makeText(this, "该图片不是gif格式", Toast.LENGTH_LONG).show()
}
else -> {
Toast.makeText(this, "gif图片读取失败:$code", Toast.LENGTH_LONG).show()
}
}
}

利用ImageDecoder结合动画图形播放动图

​ Android从9.0开始增加了新的图像解码器ImageDecoder,该解码器支持直接读取GIF文件的图像数据,通过搭配具备动画特征的图形工具Animatable即可轻松实现在App中播放GIF动图。

​ Android 9.0新增了ImageDecoder,该图像解码器不但支持播放GIF动图,也支持谷歌公司自研的WebP图片。WebP格式是谷歌公司在2010年推出的新一代图片格式,在压缩方面比JPEG格式更高效,且拥有相同的图像质量,同时WebP的图片大小比JPEG图片平均要小30%。另外,WebP也支持动图效果,ImageDecoder从WebP图片读取出Drawable对象之后即可转换成Animatable实例进行动画播放和停止播放的操作。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RequiresApi(Build.VERSION_CODES.P)
fun showAnimateDrawable(imgId:Int){
try {
//利用Android9新增的ImageDecoder获取图像来源
val source = ImageDecoder.createSource(resources,imgId)
// 从数据源中解码得到图形数据
val drawable = ImageDecoder.decodeDrawable(source)
mBinding.ivGif.setImageDrawable(drawable)
if (drawable is Animatable){
(mBinding.ivGif.drawable as Animatable).start()
}
} catch (e:java.lang.Exception){
e.printStackTrace()
}
}

淡入淡出动画

​ Android提供了过渡图形TransitionDrawable处理两张图片之间的渐变显示,即淡入淡出的动画效果。

​ 过渡图形同样需要宿主视图显示该图形,即调用图像视图的setImageDrawable方法进行图形加载操作。下面是TransitionDrawable的常用方法:

  • 构造方法:指定过渡图形的图形数组。该图形数组大小为2,包含前后两张图形
  • startTransition:开始过渡操作。这里需要先设置宿主视图再进行渐变显示。
  • resetTransition:重置过渡操作。
  • reverseTransition:倒过来执行过渡操作。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
@SuppressLint("UseCompatLoadingForDrawables")
fun showFadeAnimation(){
// 淡入淡出动画需要先定义一个图形资源数组,用于变换图片
val drawableArr = arrayOf(getDrawable(R.drawable.fade_begin),getDrawable(R.drawable.fade_end))
// 创建一个用于淡入淡出动画的过渡图形
val transDrawable = TransitionDrawable(drawableArr)
//设置过渡图形
mBinding.ivFadeAnim.setImageDrawable(transDrawable)
// 是否启用交叉淡入。启用后淡入效果更柔和
transDrawable.isCrossFadeEnabled = true
// 开始时长3秒的过渡转换
transDrawable.startTransition(3000)
}

补间动画

补间动画的种类

​ Android提供了补间动画,它允许开发者实现某个视图的动态变换,具体包括4种动画效果,分别是灰度动画平移动画缩放动画旋转动画

为什么把这4种动画称作补间动画呢?因为由开发者提供动画的起始状态值与终止状态值,然后系统按照时间推移计算中间的状态值,并自动把中间状态的视图补充到起止视图的变化过程中,自动补充中间视图的动画就被简称为“补间动画”。

​ 4种补间动画(灰度动画AlphaAnimation、平移动画TranslateAnimation、缩放动画ScaleAnimation和旋转动画RotateAnimation)都来自于共同的动画类Animation,因此同时拥有Animation的属性与方法。

Animation的常用方法:

  • setFillAfter:设置是否维持结束画面。true表示动画结束后停留在结束画面,false表示动画结束后恢复到开始画面。
  • setRepeatMode:设置动画的重播模式。Animation.RESTART表示从头开始,Animation.REVERSE表示倒过来播放。默认为Animation.RESTART。
  • setRepeatCount:设置动画的重播次数。默认值为0,表示只播放一次;值为ValueAnimator.INFINITE时表示持续重播。
  • setDuration:设置动画的持续时间,单位为毫秒
  • setInterpolator:设置动画的插值器。
  • setAnimationListener:设置动画的监听器。需实现接口AnimationListener的3个方法:
    1. onAnimationStart:在动画开始时触发。
    2. onAnimationEnd:在动画结束时触发。
    3. onAnimationRepeat:在动画重播时触发。

​ 与帧动画一样,补间动画也需要找一个宿主视图,对宿主视图施展动画效果;不同的是,帧动画的宿主视图只能是由ImageView派生出来的视图家族(图像视图、图像按钮等),而补间动画的宿主视图可以是任意视图,只要派生自View类就行

​ 给补间动画指定宿主视图的方式很简单,调用宿主对象的startAnimation方法即可命令宿主视图开始播放动画,调用宿主对象的clearAnimation方法即可要求宿主视图清除动画

补间动画初始化方式

初始化灰度动画

​ 在构造方法中指定视图透明度的前后数值,取值为0.0~1.0(0表示完全不透明,1表示完全透明)。

1
2
// 创建一个灰度动画。从完全透明变为即将不透明
val alphaAnim = AlphaAnimation(1f,0.1f)
初始化平移动画

在构造方法中指定视图在平移前后左上角的坐标值。其中,第一个参数为平移前的横坐标,第二个参数为平移后的横坐标,第三个参数为平移前的纵坐标,第四个参数为平移后的纵坐标。

1
2
// 创建一个平移动画。向左平移100dp
translateAnim = TranslateAnimation(1f, Utils.dip2px(this,-100f).toFloat(),1f,1f)
初始化缩放动画

在构造方法中指定视图横纵坐标的前后缩放比例。缩放比例取值为0.5时表示缩小到原来的二分之一,取值为2时表示放大到原来的两倍。其中,第一个参数为缩放前的横坐标比例,第二个参数为缩放后的横坐标比例,第三个参数为缩放前的纵坐标比例,第四个参数为缩放后的纵坐标比例。

1
2
// 创建一个缩放动画。宽度不变,高度变为原来的二分之一
val scaleAnim = ScaleAnimation(1f,1f,1f,0.5f)
初始化旋转动画

​ 在构造方法中指定视图的旋转角度。其中,第一个参数为旋转前的角度,第二个参数为旋转后的角度,第三个参数为圆心的横坐标类型,第四个参数为圆心横坐标的数值比例,第五个参数为圆心的纵坐标类型,第六个参数为圆心纵坐标的数值比例。

1
2
3
// 创建一个旋转动画。围绕着圆心顺时针旋转360度
val rotateAnim = RotateAnimation(0f,360f,Animation.RELATIVE_TO_SELF,
0.5f,Animation.RELATIVE_TO_SELF,0.5f)

坐标类型的取值说明:

  • ABSOLUTE:绝对位置
  • RELATIVE_TO_SELF:相对自身的位置
  • RELATIVE_TO_PARENT:相对父视图的位置

示例:

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
package com.study.animationstudy.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.RotateAnimation
import android.view.animation.ScaleAnimation
import android.view.animation.TranslateAnimation
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import com.study.animationstudy.R
import com.study.animationstudy.base.BaseActivity
import com.study.animationstudy.databinding.ActivityTweenAnimBinding
import com.study.animationstudy.util.Utils

class TweenAnimActivity : BaseActivity<ActivityTweenAnimBinding>(),AnimationListener {

// 声明四个补间动画对象
//灰度动画
lateinit var alphaAnim:Animation
//平移动画
lateinit var translateAnim:Animation
//缩放动画
lateinit var scaleAnim:Animation
//旋转动画
lateinit var rotateAnim:Animation
var isEnd = false

override fun ActivityTweenAnimBinding.initBinding() {
//初始化补间动画
initTweenAnim()
//初始化spinner
initTweenSpinner()
}

/**
* 初始化补间动画
*/
fun initTweenAnim(){
// 创建一个灰度动画。从完全透明变为即将不透明
alphaAnim = AlphaAnimation(1f,0.1f)
// 设置动画的播放时长
alphaAnim.duration = 3000
// 设置维持结束画面
alphaAnim.fillAfter = true

// 创建一个平移动画。向左平移100dp
translateAnim = TranslateAnimation(1f, Utils.dip2px(this,-100f).toFloat(),1f,1f)
// 设置动画的播放时长
translateAnim.duration = 3000
// 设置维持结束画面
translateAnim.fillAfter = true

// 创建一个缩放动画。宽度不变,高度变为原来的二分之一
scaleAnim = ScaleAnimation(1f,1f,1f,0.5f)
// 设置动画的播放时长
scaleAnim.duration = 3000
// 设置维持结束画面
scaleAnim.fillAfter = true

// 创建一个旋转动画。围绕着圆心顺时针旋转360度
rotateAnim = RotateAnimation(0f,360f,Animation.RELATIVE_TO_SELF,
0.5f,Animation.RELATIVE_TO_SELF,0.5f)
// 设置动画的播放时长
rotateAnim.duration = 3000
// 设置维持结束画面
rotateAnim.fillAfter = true
}

val tweenArr = arrayOf("灰度动画", "平移动画", "缩放动画", "旋转动画")
/**
* 初始化动画类型下拉框
*/
fun initTweenSpinner(){
val tweenArrayAdapter = ArrayAdapter<String>(this,R.layout.item_select,tweenArr)
mBinding.spTween.apply {
prompt = "请选择补间动画类型"
adapter = tweenArrayAdapter
onItemSelectedListener = object :OnItemSelectedListener{
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
// 播放指定类型的补间动画
playTweenAnim(position)
}

override fun onNothingSelected(parent: AdapterView<*>?) {

}

}
setSelection(0)
}
}

/**
* 播放指定类型的补间动画
*/
fun playTweenAnim(type:Int){
when(type){
// 灰度动画
0 -> {
// 开始播放灰度动画
mBinding.ivTweenAnim.startAnimation(alphaAnim)
// 给灰度动画设置动画事件监听器
alphaAnim.setAnimationListener(this)
}
// 平移动画
1 -> {
mBinding.ivTweenAnim.startAnimation(translateAnim)
translateAnim.setAnimationListener(this)
}
// 缩放动画
2 -> {
mBinding.ivTweenAnim.startAnimation(scaleAnim)
scaleAnim.setAnimationListener(this)
}
// 旋转动画
3 -> {
mBinding.ivTweenAnim.startAnimation(rotateAnim)
rotateAnim.setAnimationListener(this)
}
}
}

override fun onAnimationStart(animation: Animation?) {

}

override fun onAnimationEnd(animation: Animation?) {
animation?.let {
when(it){
//灰度动画
is AlphaAnimation -> {
// 创建一个灰度动画。从完全透明变为即将不透明
val alphaAnim2 = AlphaAnimation(0.1f,1f)
// 设置动画的播放时长
alphaAnim2.duration = 1000
// 设置维持结束画面
alphaAnim2.fillAfter = true
//开始播放灰度动画
mBinding.ivTweenAnim.startAnimation(alphaAnim2)
alphaAnim2.setAnimationListener(object :AnimationListener{
override fun onAnimationStart(animation: Animation?) {

}

override fun onAnimationEnd(animation: Animation?) {
playTweenAnim(0)
}

override fun onAnimationRepeat(animation: Animation?) {

}
})
}
//平移动画
is TranslateAnimation -> {
// 创建一个平移动画。向左平移100dp
val translateAnim = TranslateAnimation(Utils.dip2px(this,-100f).toFloat(),1f,1f,1f)
// 设置动画的播放时长
translateAnim.duration = 3000
// 设置维持结束画面
translateAnim.fillAfter = true
//开始播放灰度动画
mBinding.ivTweenAnim.startAnimation(translateAnim)
}
//缩放动画
is ScaleAnimation -> {
// 创建一个缩放动画。宽度不变,高度变为原来的二倍
val scaleAnim = ScaleAnimation(1f,1f,0.5f,1f)
// 设置动画的播放时长
scaleAnim.duration = 3000
// 设置维持结束画面
scaleAnim.fillAfter = true
//开始播放灰度动画
mBinding.ivTweenAnim.startAnimation(scaleAnim)
}
//旋转动画
is RotateAnimation -> {
// 创建一个旋转动画。围绕着圆心逆时针旋转360度
val rotateAnim = RotateAnimation(0f,-360f,Animation.RELATIVE_TO_SELF,
0.5f,Animation.RELATIVE_TO_SELF,0.5f)
// 设置动画的播放时长
rotateAnim.duration = 3000
// 设置维持结束画面
rotateAnim.fillAfter = true
//开始播放灰度动画
mBinding.ivTweenAnim.startAnimation(rotateAnim)
}
}
}

}

override fun onAnimationRepeat(animation: Animation?) {

}

}

补间动画的原理

​ 补间动画只提供了基本的动态变换,如果想要复杂的动画效果,比如像钟摆一样左摆一下再右摆一下,补间动画就无能为力了。如果了解补间动画的实现原理,进行适当的改造,就能使其符合实际的业务需求。

查看RotateAnimation的源码,发现除了一堆构造方法外剩下的代码只有如下3个方法:

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
/**
* Called at the end of constructor methods to initialize, if possible, values for
* the pivot point. This is only possible for ABSOLUTE pivot values.
*/
private void initializePivotPoint() {
if (mPivotXType == ABSOLUTE) {
mPivotX = mPivotXValue;
}
if (mPivotYType == ABSOLUTE) {
mPivotY = mPivotYValue;
}
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float degrees = mFromDegrees + ((mToDegrees - mFromDegrees) * interpolatedTime);
float scale = getScaleFactor();

if (mPivotX == 0.0f && mPivotY == 0.0f) {
t.getMatrix().setRotate(degrees);
} else {
t.getMatrix().setRotate(degrees, mPivotX * scale, mPivotY * scale);
}
}

@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mPivotX = resolveSize(mPivotXType, mPivotXValue, width, parentWidth);
mPivotY = resolveSize(mPivotYType, mPivotYValue, height, parentHeight);
}

​ 与动画播放有关的代码只有applyTransformation方法。该方法很简单,提供了两个输入参数:第一个参数为插值时间,即逝去的时间所占的百分比;第二个参数为转换器。方法内部根据插值时间计算当前所处的角度数值,最后使用转换器把视图旋转到该角度

补间动画的关键在于利用插值时间计算状态值。

​ 查看其他补间动画的源码,发现都与RotateAnimation的处理大同小异,对中间状态的视图变换处理不外乎以下两个步骤:

  1. 根据插值时间计算当前的状态值(如灰度、平移距离、缩放比率、旋转角度等)。
  2. 在宿主视图上使用该状态值执行变换操作。

例如:钟摆的左右摆动,这个摆动操作其实由3段旋转动画构成。

  1. 以上面的端点为圆心,钟摆以垂直向下的状态向左旋转,转到左边的某个角度停住(比如左转60度)。
  2. 钟摆从左边向右边旋转,转到右边的某个角度停住(比如右转120度,与垂直方向的夹角为60度)。
  3. 钟摆从右边再向左旋转,当其摆到垂直方向时完成一个周期的摇摆动作。

根据插值时间计算对应的角度,具体到代码实现上需要做以下两处调整:

  1. 旋转动画初始化时只有两个度数,即起始角度和终止角度。摇摆动画需要3个参数,即中间角度(既是起始角度也是终止角度)、摆到左侧的角度和摆到右侧的角度。
  2. 根据插值时间估算当前所处的角度。对于摇摆动画来说,需要做3个分支判断(对应之前3段旋转动画)。如果整个动画持续4秒,那么0~1秒为往左的旋转动画,该区间的起始角度为中间角度,终止角度为摆到左侧的角度;1~3秒为往右的旋转动画,该区间的起始角度为摆到左侧的角度,终止角度为摆到右侧的角度;3~4秒为往左的旋转动画,该区间的起始角度为摆到右侧的角度,终止角度为中间角度。

摇摆动画代码片段:

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
/**
* 在动画变换过程中调用
* @param interpolatedTime Float
* @param t Transformation
*/
override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
var degrees = 0f
// 摆到左边端点时的时间比例
val leftPos = (1f/4f)
// 摆到右边端点时的时间比例
val rightPos = (3f/4f)
when{
// 从中间线往左边端点摆
interpolatedTime <= leftPos -> {
degrees = mMiddleDegrees + ((mLeftDegrees - mMiddleDegrees) * interpolatedTime * 4)
}
// 从左边端点往右边端点摆
interpolatedTime > leftPos && interpolatedTime < rightPos -> {
// 从左边端点往右边端点摆
degrees = mLeftDegrees + (mRightDegrees - mLeftDegrees) * (interpolatedTime - leftPos) * 2
}
// 从右边端点往中间线摆
else -> {
// 从右边端点往中间线摆
degrees = mRightDegrees + (mMiddleDegrees - mRightDegrees) * (interpolatedTime - rightPos) * 4
}
}
//获得缩放比率
val scale = scaleFactor
if (mPivotX == 0.0f && mPivotY == 0.0f){
t?.matrix?.setRotate(degrees)
} else {
t?.matrix?.setRotate(degrees,mPivotX * scale,mPivotY * scale)
}
}

集合动画

​ 如一边旋转一边缩放,这时便会用到集合动画AnimationSet把几个补间动画组装起来,实现让某视图同时呈现多种动画的效果。因为集合动画与补间动画一样继承自Animation类,所以拥有补间动画的基本方法。集合动画不像一般补间动画那样提供构造方法,而是通过addAnimation方法把别的补间动画加入本集合动画中:

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
class AnimSetActivity : BaseActivity<ActivityAnimSetBinding>(),AnimationListener {

private lateinit var aniSet:AnimationSet

override fun ActivityAnimSetBinding.initBinding() {
initAnimation()
}

/**
* 初始化集合动画
*/
private fun initAnimation(){
// 创建一个灰度动画 0.0~1.0(0表示完全不透明,1表示完全透明)
val alphaAnimation = AlphaAnimation(1f,0.1f)
// 设置动画的播放时长
alphaAnimation.duration = 3000
// 设置维持结束画面
alphaAnimation.fillAfter = true
// 创建一个平移动画 向左平移200,第一个参数是原始横坐标,第二个参数是平移后的的横坐标,第三个参数是原始纵坐标,第四个参数是平移后的纵坐标
val translateAnimation = TranslateAnimation(1f,-200f,1f,1f)
// 设置动画的播放时长
translateAnimation.duration = 3000
// 设置维持结束画面
translateAnimation.fillAfter = true
// 创建一个缩放动画,第一个参数是缩放前的横坐标比例,第二个是缩放后的横坐标比例,第三个是缩放前的纵坐标比例,第四个是缩放后的纵坐标比例
val scaleAnimation = ScaleAnimation(1f,1f,1f,0.5f)
// 设置动画的播放时长
scaleAnimation.duration = 3000
// 设置维持结束画面
scaleAnimation.fillAfter = true
// 创建一个旋转动画
val rotateAnimation = RotateAnimation(0f,360f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f)
// 设置动画的播放时长
rotateAnimation.duration = 3000
// 设置维持结束画面
rotateAnimation.fillAfter = true
// 创建一个集合动画
aniSet = AnimationSet(true)
// 下面在代码中添加集合动画
aniSet.addAnimation(alphaAnimation)
aniSet.addAnimation(translateAnimation)
aniSet.addAnimation(scaleAnimation)
aniSet.addAnimation(rotateAnimation)
aniSet.fillAfter = true
startAnim()
}

/**
* 开始播放集合动画
*/
private fun startAnim(){
mBinding.aniSet.startAnimation(aniSet)
aniSet.setAnimationListener(this)
}

override fun onAnimationStart(animation: Animation?) {

}

override fun onAnimationEnd(animation: Animation?) {
// 原集合动画播放完毕,接着播放倒过来的集合动画
if (animation?.equals(aniSet) == true){
// 创建一个灰度动画 0.0~1.0(0表示完全不透明,1表示完全透明)
val alphaAnimation = AlphaAnimation(0.1f,1f)
// 设置动画的播放时长
alphaAnimation.duration = 3000
// 设置维持结束画面
alphaAnimation.fillAfter = true
// 创建一个平移动画 向左平移200,第一个参数是原始横坐标,第二个参数是平移后的的横坐标,第三个参数是原始纵坐标,第四个参数是平移后的纵坐标
val translateAnimation = TranslateAnimation(-200f,1f,1f,1f)
// 设置动画的播放时长
translateAnimation.duration = 3000
// 设置维持结束画面
translateAnimation.fillAfter = true
// 创建一个缩放动画,第一个参数是缩放前的横坐标比例,第二个是缩放后的横坐标比例,第三个是缩放前的纵坐标比例,第四个是缩放后的纵坐标比例
val scaleAnimation = ScaleAnimation(1f,1f,0.5f,1f)
// 设置动画的播放时长
scaleAnimation.duration = 3000
// 设置维持结束画面
scaleAnimation.fillAfter = true
// 创建一个旋转动画,围绕着圆心逆时针旋转360度
val rotateAnimation = RotateAnimation(0f,-360f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f)
// 设置动画的播放时长
rotateAnimation.duration = 3000
// 设置维持结束画面
rotateAnimation.fillAfter = true
// 创建一个集合动画
val aniSet = AnimationSet(true)
// 下面在代码中添加集合动画
aniSet.addAnimation(alphaAnimation)
aniSet.addAnimation(translateAnimation)
aniSet.addAnimation(scaleAnimation)
aniSet.addAnimation(rotateAnimation)
aniSet.fillAfter = true
mBinding.aniSet.startAnimation(aniSet)
}
}

override fun onAnimationRepeat(animation: Animation?) {

}
}

属性动画

常规的属性动画

​ 视图View类虽有许多状态属性,但补间动画只对其中6种属性进行操作:

​ 如果要求对视图的背景颜色做渐变处理,补间动画就无能为力了。为此,Android又引入了属性动画ObjectAnimator。属性动画突破了补间动画的局限,允许视图的所有属性都能实现渐变的动画效果,例如背景颜色、文字颜色、文字大小等。只要设定某属性的起始值与终止值、渐变的持续时间,属性动画即可实现渐变效果。

​ 下面是ObjectAnimator的常用方法:

  • ofInt:定义整型属性的属性动画。
  • ofFloat:定义浮点型属性的属性动画。
  • ofArgb:定义颜色属性的属性动画。
  • ofObject:定义对象属性的属性动画,用于不是上述三种类型的属性,例如Rect对象。

​ 以上4个of方法的第一个参数为宿主视图对象,第二个参数为需要变化的属性名称,从第三个参数开始以及后面的参数为属性变化的各个状态值。注意,of方法后面的参数个数是变化的。如果第3个参数是状态A、第4个参数是状态B,属性动画就从A状态变为B状态;如果第3个参数是状态A、第4个参数是状态B、第5个参数是状态C,属性动画就先从A状态变为B状态,再从B状态变为C状态。

  • setRepeatMode:设置动画的重播模式。ValueAnimator.RESTART表示从头开始,ValueAnimator.REVERSE表示倒过来播放。默认值为ValueAnimator.RESTART。
  • setRepeatCount:设置动画的重播次数。默认值为0,表示只播放一次;值为ValueAnimator.INFINITE时表示持续重播。
  • setDuration:设置动画的持续播放时间,单位为毫秒。
  • setInterpolator:设置动画的插值器。
  • setEvaluator:设置动画的估值器。
  • start:开始播放动画。
  • cancel:取消播放动画。
  • end:结束播放动画。
  • pause:暂停播放动画。
  • resume:恢复播放动画。
  • reverse:倒过来播放动画。
  • isRunning:判断动画是否在播放。注意,暂停时,isRunning方法仍然返回true。
  • isPaused:判断动画是否被暂停。
  • isStarted:判断动画是否已经开始。注意,曾经播放与正在播放都算已经开始。
  • addListener:添加动画监听器,需实现接口AnimatorListener的4个方法。
    1. onAnimationStart:在动画开始播放时触发。
    2. onAnimationEnd:在动画结束播放时触发。
    3. onAnimationCancel:在动画取消播放时触发。
    4. onAnimationRepeat:在动画重播时触发。

案例:

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
class ObjectAnimActivity : BaseActivity<ActivityObjectAnimBinding>() {
// 声明四个属性动画对象
private lateinit var alphaAnim:ObjectAnimator
private lateinit var translateAnim:ObjectAnimator
private lateinit var scaleAnim:ObjectAnimator
private lateinit var rotateAnim:ObjectAnimator
private val objectArray = arrayOf("灰度动画", "平移动画", "缩放动画", "旋转动画", "裁剪动画")

override fun ActivityObjectAnimBinding.initBinding() {
initObjectAnim()
initObjectSpinner()
}

/**
* 初始化属性动画
*/
private fun initObjectAnim(){
// 构造一个在透明度上变化的属性动画
alphaAnim = ObjectAnimator.ofFloat(mBinding.ivObjectAnim,"alpha",1f,0.1f,1f)
// 构造一个在横轴上平移的属性动画
translateAnim = ObjectAnimator.ofFloat(mBinding.ivObjectAnim,"translationX",0f,-200f,0f,200f,0f)
// 构造一个在纵轴上缩放的属性动画
scaleAnim = ObjectAnimator.ofFloat(mBinding.ivObjectAnim,"scaleY",1f,0.5f,1f)
// 构造一个围绕中心点旋转的属性动画
rotateAnim = ObjectAnimator.ofFloat(mBinding.ivObjectAnim,"rotation",0f,360f,0f)
}

private fun initObjectSpinner(){
val objectAdapter = ArrayAdapter<String>(this,R.layout.item_select,objectArray)
mBinding.spObject.apply {
prompt = "请选择属性动画类型"
adapter = objectAdapter
onItemSelectedListener = object: OnItemSelectedListener{
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
playObjectAnim(position)
}

override fun onNothingSelected(parent: AdapterView<*>?) {

}

}
}
}

/**
* 播放指定类型的属性动画
* @param type Int
*/
private fun playObjectAnim(type:Int){
var anim:ObjectAnimator? = null
when(type){
// 灰度动画
0 -> anim = alphaAnim
// 平移动画
1 -> anim = translateAnim
// 缩放动画
2 -> anim = scaleAnim
// 旋转动画
3 -> anim = rotateAnim
// 裁剪动画
4 -> {
val width = mBinding.ivObjectAnim.width
val height = mBinding.ivObjectAnim.height
// 构造一个从四周向中间裁剪的属性动画
val clipAnim = ObjectAnimator.ofObject(mBinding.ivObjectAnim,"clipBounds",
RectEvaluator(), Rect(0, 0, width, height),
Rect(width / 3, height / 3, width / 3 * 2, height / 3 * 2),
Rect(0, 0, width, height))
anim = clipAnim
}
}
anim?.apply {
// 设置动画的播放时长
duration = 3000
// 开始播放属性动画
start()
}
}

}

属性动画组合

​ 补间动画可以通过集合动画AnimationSet组装多种动画效果,属性动画也有类似的做法,即通过属性动画组合AnimatorSet组装多种属性动画。

AnimatorSet的常用方法:

  • setDuration:设置动画组合的持续时间,单位为毫秒。

  • setInterpolator:设置动画组合的插值器。

  • play:设置当前动画。该方法返回一个AnimatorSet.Builder对象,可对该对象调用组装方法添加新动画,从而实现动画组装功能。下面是Builder的组装方法说明。

    1. with:指定该动画与当前动画一起播放。
    2. before:指定该动画在当前动画之前播放。
    3. after:指定该动画在当前动画之后播放。
  • start:开始播放动画组合。

  • pause:暂停播放动画组合。

  • resume:恢复播放动画组合。

  • cancel:取消播放动画组合。

  • end:结束播放动画组合。

  • isRunning:判断动画组合是否在播放。

  • isStarted:判断动画组合是否已经开始。

示例代码:

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
class ObjectGroupActivity : BaseActivity<ActivityObjectGroupBinding>(),OnClickListener,AnimatorListener {

// 声明一个属性动画组合对象
private lateinit var animSet:AnimatorSet
private var isPaused = false

override fun ActivityObjectGroupBinding.initBinding() {
mBinding.ivObjectGroup.setOnClickListener(this@ObjectGroupActivity)
initObjectAnim()
}

private fun initObjectAnim(){
// 构造一个在横轴上平移的属性动画
val anim1 = ObjectAnimator.ofFloat(mBinding.ivObjectGroup,"translationX",0f,100f)
// 构造一个在透明度上变化的属性动画
val anim2 = ObjectAnimator.ofFloat(mBinding.ivObjectGroup,"alpha",1f,0.1f,1f,0.5f,1f)
// 构造一个围绕中心点旋转的属性动画
val anim3 = ObjectAnimator.ofFloat(mBinding.ivObjectGroup,"rotation",0f,360f)
// 构造一个在纵轴上缩放的属性动画
val anim4 = ObjectAnimator.ofFloat(mBinding.ivObjectGroup,"scaleY",1f,0.5f,1f)
// 构造一个在横轴上平移的属性动画
val anim5 = ObjectAnimator.ofFloat(mBinding.ivObjectGroup,"translationX",100f,0f)
// 创建一个属性动画组合
animSet = AnimatorSet()
// 把指定的属性动画添加到属性动画组合
val builder = animSet.play(anim2)
// 动画播放顺序为:先执行anim1,再一起执行anim2、anim3、anim4,最后执行anim5
builder.with(anim3).with(anim4).after(anim1).before(anim5)
// 设置动画的播放时长
animSet.duration = 4500
// 开始播放属性动画
animSet.start()
// 给属性动画添加动画事件监听器
animSet.addListener(this)

}

override fun onClick(v: View?) {
when(v?.id){
mBinding.ivObjectGroup.id -> {
if (animSet.isStarted){
if (!isPaused){
Log.d("Tag","暂停播放")
animSet.pause()
} else {
Log.d("Tag","继续播放")
animSet.resume()
}
// 恢复播放属性动画
isPaused = !isPaused
} else {// 属性动画尚未开始播放
Log.d("Tag","开始播放")
animSet.start()
}
}
}
}

override fun onAnimationStart(animation: Animator?) {

}

override fun onAnimationEnd(animation: Animator?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
// 设置当前播放的时间点
animSet.currentPlayTime = 0
// 从动画尾巴开始倒播至setCurrentPlayTime设置的时间点
animSet.reverse()
}
}

override fun onAnimationCancel(animation: Animator?) {

}

override fun onAnimationRepeat(animation: Animator?) {

}

}

插值器和估值器

插值器用来控制属性值的变化速率,也可以理解为动画播放的速度默认是先加速再减速(AccelerateDecelerateInterpolator)。若要给动画播放指定某种速率形式(比如匀速播放),调用setInterpolator方法设置对应的插值器实现类即可,无论是补间动画、集合动画、属性动画还是属性动画组合,都可以设置插值器。

插值器实现类的说明:

估值器专用于属性动画,主要描述该属性的数值变化要采用什么单位,比如整数类型的渐变数值要取整,颜色的渐变数值为ARGB格式的颜色对象,矩形的渐变数值为Rect对象等。要给属性动画设置估值器,调用属性动画对象的setEvaluator方法即可。

估值器实现类的说明:

​ 一般情况下,无须单独设置属性动画的估值器,使用系统默认的估值器即可。如果属性类型不是int、float、argb三种,只能通过ofObject方法构造属性动画对象,就必须指定该属性的估值器,否则系统不知道如何计算渐变属性值。

属性类型与估值器的对应关系:

示例:

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
class InterpolatorActivity : BaseActivity<ActivityInterpolatorBinding>(),AnimatorListener {
// 声明四个属性动画对象
private lateinit var animAcce:ObjectAnimator
private lateinit var animDece:ObjectAnimator
private lateinit var animLinear:ObjectAnimator
private lateinit var animBounce:ObjectAnimator

private val interpolatorArray = arrayOf("背景色+加速插值器+颜色估值器", "旋转+减速插值器+浮点型估值器",
"裁剪+匀速插值器+矩形估值器", "文字大小+震荡插值器+浮点型估值器")

override fun ActivityInterpolatorBinding.initBinding() {
//初始化属性动画
initObjectAnim()
//初始化插值器类型的下拉框
initInterpolatorSpinner()
}

/**
* 初始化插值器类型的下拉框
*/
fun initInterpolatorSpinner(){
val interpolatorAdapter = ArrayAdapter(this,R.layout.item_select,interpolatorArray)
mBinding.spInterpolator.apply {
prompt = "请选择插值器类型"
adapter = interpolatorAdapter
onItemSelectedListener = object : OnItemSelectedListener{
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
// 根据插值器类型展示属性动画
showInterpolator(position)
}

override fun onNothingSelected(parent: AdapterView<*>?) {

}

}
}
}

//初始化属性动画
fun initObjectAnim(){
//构造一个在背景色上变化的属性动画
animAcce = ObjectAnimator.ofInt(mBinding.tvInterpolator,"backgroundColor",Color.RED,Color.GRAY)
//给属性动画设置加速插值器
animAcce.interpolator = AccelerateInterpolator()
//给属性动画设置颜色估值器
animAcce.setEvaluator(ArgbEvaluator())

//构造一个围绕中心点旋转的属性动画
animDece = ObjectAnimator.ofFloat(mBinding.tvInterpolator,"rotation",0f,360f)
//给属性动画设置减速插值器
animDece.interpolator = DecelerateInterpolator()
//给属性动画设置浮点型估值器
animDece.setEvaluator(FloatEvaluator())

//构造一个在文字大小上变化的属性动画
animBounce = ObjectAnimator.ofFloat(mBinding.tvInterpolator,"textSize",20f,60f)
//给属性动画设置震荡插值器
animBounce.interpolator = BounceInterpolator()
//给属性动画设置浮点型估值器
animBounce.setEvaluator(FloatEvaluator())
}


/**
* 根据插值器类型展示属性动画
*/
fun showInterpolator(type:Int){
var anim:ObjectAnimator? = null
when(type){
// 背景色+加速插值器+颜色估值器
0 -> anim = animAcce
// 旋转+减速插值器+浮点型估值器
1 -> anim = animDece
// 裁剪+匀速插值器+矩形估值器
2 -> {
val width = mBinding.tvInterpolator.width
val height = mBinding.tvInterpolator.height
// 构造一个从四周向中间裁剪的属性动画,同时指定了矩形估值器RectEvaluator
animLinear = ObjectAnimator.ofObject(mBinding.tvInterpolator,"clipBounds",
RectEvaluator(),Rect(0,0,width,height),
Rect(width/3,height/3,width/3*2,height/3*2),
Rect(0,0,width,height))
// 给属性动画设置匀速插值器
animLinear.interpolator = LinearInterpolator()
anim = animLinear
}
// 文字大小+震荡插值器+浮点型估值器
3 -> {
anim = animBounce
// 给属性动画添加动画事件监听器。目的是在动画结束时恢复文字大小
anim.addListener(this)
}
}
// 设置动画的播放时长
anim?.duration = 2000
anim?.start()
}

/**
* 在属性动画开始播放时触发
* @param animation Animator
*/
override fun onAnimationStart(animation: Animator?) {

}

override fun onAnimationEnd(animation: Animator?) {
if (animation?.equals(animBounce) == true){
// 构造一个在文字大小上变化的属性动画
val anim = ObjectAnimator.ofFloat(mBinding.tvInterpolator,"textSize",60f,20f)
// 给属性动画设置震荡插值器
anim.interpolator = BounceInterpolator()
// 给属性动画设置浮点型估值器
anim.setEvaluator(FloatEvaluator())
anim.duration = 2000
anim.start()
}
}

override fun onAnimationCancel(animation: Animator?) {

}

override fun onAnimationRepeat(animation: Animator?) {

}

}

利用估值器实现弹幕动画

  1. 定义一个间距估值器,实现接口TypeEvaluator的evaluate方法,并在该方法中返回指定时间点的间距数值。
  2. 调用ValueAnimator类的ofObject方法,根据间距估值器、开始位置和结束位置构建属性动画对象。
  3. 调用属性动画对象的addUpdateListener方法设置刷新监听器,在监听器内部获取当前的间距数值,并调整视图此时的布局参数。

需要自定义弹幕视图,其内部在垂直方向排列,每行放置一个相对布局。

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
class BarrageView(context: Context,attrs:AttributeSet?):LinearLayout(context, attrs) {

constructor(context: Context):this(context,null)

companion object{
const val TAG = "BarrageView"
class MarginEvaluator : TypeEvaluator<Int> {
override fun evaluate(fraction: Float, startValue: Int, endValue: Int): Int {
return (startValue * (1 - fraction) + endValue * fraction).toInt()
}
}
}
// 弹幕行数
private var mRowCount = 5
// 文字大小
private var mTextSize = 15
// 每行的相对布局列表
private val mLayoutList = ArrayList<RelativeLayout>()
// 视图宽度
private var mWidth = 0
// 最近两次的弹幕位置
private var mLastPos1 = -1
private var mLastPos2 = -1
private val COLOR_ARRAY = arrayOf(
Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW,
Color.CYAN, Color.MAGENTA, Color.LTGRAY, Color.GRAY,
Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW,
Color.CYAN, Color.MAGENTA, Color.LTGRAY, Color.GRAY)

init {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.TRANSPARENT)
for (i in 0 until mRowCount){
val layout = RelativeLayout(context)
val params = RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,Utils.dip2px(context,40f))
layout.layoutParams = params
layout.setBackgroundColor(Color.TRANSPARENT)
mLayoutList.add(layout)
// 添加至当前视图
addView(layout)
}
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
// 获取视图的实际宽度
mWidth = measuredWidth
}

/**
* 获取本次弹幕的位置。不跟最近两次在同一行,避免挨得太近
* @return Int
*/
private fun getPos():Int{
var pos = 0
do {
pos = Random().nextInt(mRowCount)
}while (pos == mLastPos1 || pos == mLastPos2)
mLastPos2 = mLastPos1
mLastPos1 = pos
return pos
}

/**
* 给弹幕视图添加评论
*/
fun addComment(comment:String){
// 获取随机位置的相对布局
val layout = mLayoutList[getPos()]
// 获取评论文字的文本视图
val tv = getCommentView(comment)
val textWidth:Float = MeasureUtil.getTextWidth(comment,Utils.dip2px(context,
mTextSize.toFloat()
).toFloat())
layout.addView(tv)
// 根据估值器和起止位置创建一个属性动画
val anim = ValueAnimator.ofObject(MarginEvaluator(),-textWidth,mWidth)
// 添加属性动画的刷新监听器
anim.addUpdateListener {
//获取动画的当前值
val margin = it.animatedValue
val tvParams = tv.layoutParams as RelativeLayout.LayoutParams
tvParams.rightMargin = margin as Int
if (margin > mWidth - textWidth){
tvParams.leftMargin = (mWidth - textWidth - margin).toInt()
}
// 设置文本视图的布局参数
tv.layoutParams = tvParams
}
//设置动画的播放目标
anim.setTarget(tv)
//设置动画的播放时长
anim.duration = 5000
//设置属性动画的插值器
anim.interpolator = LinearInterpolator()
//属性动画开始播放
anim.start()
//添加属性动画的监听器
anim.addListener(object :AnimatorListener{
override fun onAnimationStart(animation: Animator?) {

}

override fun onAnimationEnd(animation: Animator?) {
layout.removeView(tv)
}

override fun onAnimationCancel(animation: Animator?) {

}

override fun onAnimationRepeat(animation: Animator?) {

}
})
}

/**
* 获取评论内容的文本视图
*/
private fun getCommentView(content:String):TextView{
val tv = TextView(context)
tv.apply {
text = content
textSize = mTextSize.toFloat()
setTextColor(getColorByContent(content))
isSingleLine = true
setBackgroundColor(Color.TRANSPARENT)
val tvParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT)
// 垂直方向居中
tvParams.addRule(RelativeLayout.CENTER_VERTICAL)
//与上级布局右对齐
tvParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
//设置文本视图的布局参数
tv.layoutParams = tvParams
}
return tv
}

/**
* 根据昵称获取对应的头像
* @param content String
* @return Int
*/
private fun getColorByContent(content:String): Int {
val md5:String = MD5Util.encrypt(content)
val lastChar = md5[md5.lastIndex]
val pos = if(lastChar >= 'A') lastChar - 'A'+10 else lastChar - '0'
return COLOR_ARRAY[pos]
}
}

遮罩动画及滚动器

画布的绘图层次

​ 画布Canvas上的绘图操作都是在同一个图层上进行的,这意味着如果存在重叠区域,后面绘制的图形就必然覆盖前面的图形。

图层模式的取值说明:

假设圆圈是先绘制的下层图形,正方形是后绘制的上层图形:

示例:

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
class LayerView(context: Context,attrs:AttributeSet):View(context, attrs) {

companion object{
const val TAG = "LayerView"
}
//声明上层的画笔对象
private val mUpPaint = Paint()
//声明下层的画笔对象
private val mDownPaint = Paint()
//声明遮罩的画笔对象
private val mMaskPaint = Paint()
//是否只绘制轮廓
private var onlyLine = true
//绘图模式
private lateinit var mMode:PorterDuff.Mode

init {
mUpPaint.strokeWidth = 5f
mUpPaint.color = Color.CYAN
mDownPaint.strokeWidth = 5f
mDownPaint.color = Color.RED
}

public fun setMode(mode:PorterDuff.Mode){
mMode = mode
onlyLine = false
mUpPaint.style = Paint.Style.FILL
mDownPaint.style = Paint.Style.FILL
// 立即刷新视图(线程安全方式)
postInvalidate()
}

@SuppressLint("DrawAllocation")
override fun onDraw(canvas: Canvas?) {
//获取视图的实际宽度
val width = measuredWidth
//获取视图的实际高度
val height = measuredHeight
// 只绘制轮廓
if (onlyLine){
canvas?.apply {
drawRect((width/3).toFloat(), (height/3).toFloat(),
(width*9/10).toFloat(), (height*9/10).toFloat(),mUpPaint)
drawCircle((width/3).toFloat(), (height/3).toFloat(),
(height/3).toFloat(),mDownPaint)
}
} else if(mMode != null) {
// 绘制混合后的图像
// 创建一个遮罩位图
val mask = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)
// 创建一个遮罩画布
val canvasMask = Canvas(mask)
//先绘制上层的矩形
canvasMask.drawRect(
(width/3).toFloat(), (height/3).toFloat(),
(width*9/10).toFloat(), (height*9/10).toFloat(),mUpPaint)
//设置离屏缓存
// 设置离屏缓存
val saveLayer = canvas!!.saveLayer(
0f,
0f,
width.toFloat(),
height.toFloat(),
null,
Canvas.ALL_SAVE_FLAG
)
// 再绘制下层的圆形
// 再绘制下层的圆形
canvas.drawCircle(
(width / 3).toFloat(),
(height / 3).toFloat(),
(height / 3).toFloat(),
mDownPaint
)
mMaskPaint.xfermode = PorterDuffXfermode(mMode) // 设置混合模式

canvas.drawBitmap(mask, 0f, 0f, mMaskPaint) // 绘制源图像的遮罩

mMaskPaint.xfermode = null // 还原混合模式

canvas.restoreToCount(saveLayer) // 还原画布
}
}

// 只显示线条轮廓
fun setOnlyLine() {
onlyLine = true
mUpPaint.style = Paint.Style.STROKE // 设置画笔的类型
mDownPaint.style = Paint.Style.STROKE // 设置画笔的类型
postInvalidate() // 立即刷新视图(线程安全方式)
}
}

实现百叶窗视图

​ 首先定义一个百叶窗视图,并重写onDraw方法,给遮罩画布描绘若干矩形叶片,每次绘制的叶片大小由比率参数决定。

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
//百叶窗视图
@SuppressLint("DrawAllocation")
public class ShutterView extends View {
private final static String TAG = "ShutterView";
private Paint mPaint = new Paint(); // 声明一个画笔对象
private int mOriention = LinearLayout.HORIZONTAL; // 动画方向
private int mLeafCount = 10; // 叶片的数量
private PorterDuff.Mode mMode = PorterDuff.Mode.DST_IN; // 绘图模式为只展示交集
private Bitmap mBitmap; // 声明一个位图对象
private int mRatio = 0; // 绘制的比率

public ShutterView(Context context) {
this(context, null);
}

public ShutterView(Context context, AttributeSet attrs) {
super(context, attrs);
}

// 设置百叶窗的方向
public void setOriention(int oriention) {
mOriention = oriention;
}

// 设置百叶窗的叶片数量
public void setLeafCount(int leaf_count) {
mLeafCount = leaf_count;
}

// 设置绘图模式
public void setMode(PorterDuff.Mode mode) {
mMode = mode;
}

// 设置位图对象
public void setImageBitmap(Bitmap bitmap) {
mBitmap = bitmap;
}

// 设置绘图比率
public void setRatio(int ratio) {
mRatio = ratio;
postInvalidate(); // 立即刷新视图(线程安全方式)
}

@Override
protected void onDraw(Canvas canvas) {
if (mBitmap == null) {
return;
}
int width = getMeasuredWidth(); // 获取视图的实际宽度
int height = getMeasuredHeight(); // 获取视图的实际高度
// 创建一个遮罩位图
Bitmap mask = Bitmap.createBitmap(width, height, mBitmap.getConfig());
Canvas canvasMask = new Canvas(mask); // 创建一个遮罩画布
for (int i = 0; i < mLeafCount; i++) {
if (mOriention == LinearLayout.HORIZONTAL) { // 水平方向
int column_width = (int) Math.ceil(width * 1f / mLeafCount);
int left = column_width * i;
int right = left + column_width * mRatio / 100;
// 在遮罩画布上绘制各矩形叶片
canvasMask.drawRect(left, 0, right, height, mPaint);
} else { // 垂直方向
int row_height = (int) Math.ceil(height * 1f / mLeafCount);
int top = row_height * i;
int bottom = top + row_height * mRatio / 100;
// 在遮罩画布上绘制各矩形叶片
canvasMask.drawRect(0, top, width, bottom, mPaint);
}
}
// 设置离屏缓存
int saveLayer = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
Rect rect = new Rect(0, 0, width, width * mBitmap.getHeight() / mBitmap.getWidth());
canvas.drawBitmap(mBitmap, null, rect, mPaint); // 绘制目标图像
mPaint.setXfermode(new PorterDuffXfermode(mMode)); // 设置混合模式
canvas.drawBitmap(mask, 0, 0, mPaint); // 再绘制源图像的遮罩
mPaint.setXfermode(null); // 还原混合模式
canvas.restoreToCount(saveLayer); // 还原画布
}

}

​ 然后在布局文件中添加ShutterView节点,并在对应的活动页面调用setOriention方法设置百叶窗的方向,调用setLeafCount方法设置百叶窗的叶片数量。再利用属性动画渐进设置ratio属性,使整个百叶窗的各个叶片逐步合上,从而实现合上百叶窗的动画特效。

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
class ShutterActivity : BaseActivity<ActivityShutterBinding>() {

private val shutterArray = arrayOf("水平五叶", "水平十叶", "水平二十叶",
"垂直五叶", "垂直十叶", "垂直二十叶")


override fun ActivityShutterBinding.initBinding() {
initView()
initLayerSpinner()
}

private fun initView(){
val bitmap = BitmapFactory.decodeResource(resources,R.drawable.dlam)
// 设置百叶窗视图的位图对象
mBinding.svShutter.setImageBitmap(bitmap)
val params = mBinding.svShutter.layoutParams
params.height = Utils.getScreenWidth(this) * bitmap.height / bitmap.width
// 设置百叶窗视图的布局参数
mBinding.svShutter.layoutParams = params
}

private fun initLayerSpinner(){
val modeAdapter = ArrayAdapter(this,R.layout.item_select,shutterArray)
mBinding.spShutter.apply {
prompt = "请选择百叶窗动画类型"
adapter = modeAdapter
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
// 设置百叶窗视图的动画方向
mBinding.svShutter.setOriention(if (position<3) LinearLayout.HORIZONTAL else LinearLayout.VERTICAL)
if (position ==0 || position ==3){
// 设置百叶窗的叶片数量
mBinding.svShutter.setLeafCount(5)
} else if (position == 1 || position == 4){
mBinding.svShutter.setLeafCount(10)
} else if (position == 2 || position == 5){
mBinding.svShutter.setLeafCount(20)
}
// 构造一个按比率逐步展开的属性动画
val anim = ObjectAnimator.ofInt(mBinding.svShutter,"ratio",0,100)
// 设置动画的播放时长
anim.duration = 3000
anim.start()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
setSelection(0)
}
}
}

实现马赛克动画

基于同样的绘制原理,可以依样画瓢实现马赛克动画:

马赛克视图:

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
/**
* 马赛克动画视图
*/
@SuppressLint("DrawAllocation")
public class MosaicView extends View {
private final static String TAG = "MosaicView";
private Paint mPaint = new Paint(); // 声明一个画笔对象
private int mOriention = LinearLayout.HORIZONTAL; // 动画方向
private int mGridCount = 20; // 格子的数量
private PorterDuff.Mode mMode = PorterDuff.Mode.DST_IN; // 绘图模式为只展示交集
private Bitmap mBitmap; // 声明一个位图对象
private int mRatio = 0; // 绘制的比率
private int mOffset = 5; // 偏差的比例
private float FENMU = 100; // 计算比例的分母,其实分母的英语叫做denominator

public MosaicView(Context context) {
this(context, null);
}

public MosaicView(Context context, AttributeSet attrs) {
super(context, attrs);
}

// 设置马赛克的方向
public void setOriention(int oriention) {
mOriention = oriention;
}

// 设置马赛克的格子数量
public void setGridCount(int grid_count) {
mGridCount = grid_count;
}

// 设置偏差比例
public void setOffset(int offset) {
mOffset = offset;
}

// 设置绘图模式
public void setMode(PorterDuff.Mode mode) {
mMode = mode;
}

// 设置位图对象
public void setImageBitmap(Bitmap bitmap) {
mBitmap = bitmap;
}

// 设置绘图比率
public void setRatio(int ratio) {
mRatio = ratio;
postInvalidate(); // 立即刷新视图(线程安全方式)
}

@Override
protected void onDraw(Canvas canvas) {
if (mBitmap == null) {
return;
}
int width = getMeasuredWidth(); // 获取视图的实际宽度
int height = getMeasuredHeight(); // 获取视图的实际高度
// 创建一个遮罩位图
Bitmap mask = Bitmap.createBitmap(width, height, mBitmap.getConfig());
Canvas canvasMask = new Canvas(mask); // 创建一个遮罩画布
if (mOriention == LinearLayout.HORIZONTAL) { // 水平方向
float grid_width = height / mGridCount;
int column_count = (int) Math.ceil(width / grid_width);
int total_count = mGridCount * column_count;
int draw_count = 0;
for (int i = 0; i < column_count; i++) {
for (int j = 0; j < mGridCount; j++) {
int now_ratio = (int) ((mGridCount * i + j) * FENMU / total_count);
if (now_ratio < mRatio - mOffset
|| (now_ratio >= mRatio - mOffset && now_ratio < mRatio &&
((j % 2 == 0 && i % 2 == 0) || (j % 2 == 1 && i % 2 == 1)))
|| (now_ratio >= mRatio && now_ratio < mRatio + mOffset &&
((j % 2 == 0 && i % 2 == 1) || (j % 2 == 1 && i % 2 == 0)))) {
int left = (int) (grid_width * i);
int top = (int) (grid_width * j);
// 在遮罩画布上绘制各方形格子
canvasMask.drawRect(left, top, left + grid_width, top + grid_width, mPaint);
if (j < mGridCount) {
draw_count++;
}
if (draw_count * FENMU / total_count > mRatio) {
break;
}
}
}
if (draw_count * FENMU / total_count > mRatio) {
break;
}
}
} else { // 垂直方向
float grid_width = width / mGridCount;
int row_count = (int) Math.ceil(height / grid_width);
int total_count = mGridCount * row_count;
int draw_count = 0;
for (int i = 0; i < row_count; i++) {
for (int j = 0; j < mGridCount; j++) {
int now_ratio = (int) ((mGridCount * i + j) * FENMU / total_count);
if (now_ratio < mRatio - mOffset
|| (now_ratio >= mRatio - mOffset && now_ratio < mRatio &&
((j % 2 == 0 && i % 2 == 0) || (j % 2 == 1 && i % 2 == 1)))
|| (now_ratio >= mRatio && now_ratio < mRatio + mOffset &&
((j % 2 == 0 && i % 2 == 1) || (j % 2 == 1 && i % 2 == 0)))) {
int left = (int) (grid_width * j);
int top = (int) (grid_width * i);
// 在遮罩画布上绘制各方形格子
canvasMask.drawRect(left, top, left + grid_width, top + grid_width, mPaint);
if (j < mGridCount) {
draw_count++;
}
if (draw_count * FENMU / total_count > mRatio) {
break;
}
}
}
if (draw_count * FENMU / total_count > mRatio) {
break;
}
}
}
// 设置离屏缓存
int saveLayer = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
Rect rect = new Rect(0, 0, width, width * mBitmap.getHeight() / mBitmap.getWidth());
canvas.drawBitmap(mBitmap, null, rect, mPaint); // 绘制目标图像
mPaint.setXfermode(new PorterDuffXfermode(mMode)); // 设置混合模式
canvas.drawBitmap(mask, 0, 0, mPaint); // 再绘制源图像的遮罩
mPaint.setXfermode(null); // 还原混合模式
canvas.restoreToCount(saveLayer); // 还原画布
}

}

​ 在布局文件中添加MosaicView节点,并在对应的活动页面调用setGridCount方法设置马赛克的格子数量,再利用属性动画渐进设置ratio属性,使得视图中的马赛克逐步清晰显现。

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
class MosaicActivity : BaseActivity<ActivityMosaicBinding>() {

private val mosaicArray = arrayOf("水平二十格", "水平三十格", "水平四十格",
"垂直二十格", "垂直三十格", "垂直四十格")

override fun ActivityMosaicBinding.initBinding() {
initView()
initLayerSpinner()
}

private fun initView(){
val bitmap = BitmapFactory.decodeResource(resources,R.drawable.dlam)
// 设置百叶窗视图的位图对象
mBinding.mvMosaic.setImageBitmap(bitmap)
val params = mBinding.mvMosaic.layoutParams
params.height = Utils.getScreenWidth(this) * bitmap.height / bitmap.width
// 设置百叶窗视图的布局参数
mBinding.mvMosaic.layoutParams = params
}

private fun initLayerSpinner(){
val modeAdapter = ArrayAdapter(this,R.layout.item_select,mosaicArray)
mBinding.spMosaic.apply {
prompt = "请选择百叶窗动画类型"
adapter = modeAdapter
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
// 设置马赛克视图的动画方向
mBinding.mvMosaic.setOriention(if (position<3) LinearLayout.HORIZONTAL else LinearLayout.VERTICAL)
if (position ==0 || position ==3){
// 设置马赛克的格子数量
mBinding.mvMosaic.setGridCount(20)
} else if (position == 1 || position == 4){
mBinding.mvMosaic.setGridCount(30)
} else if (position == 2 || position == 5){
mBinding.mvMosaic.setGridCount(40)
}
// 起始值和结束值要超出一些范围,这样头尾的马赛克看起来才是连贯的
val offset = 5
// 设置偏差比例
mBinding.mvMosaic.setOffset(offset)
// 构造一个按比率逐步展开的属性动画
val anim = ObjectAnimator.ofInt(mBinding.mvMosaic,"ratio",0 - offset,101 + offset)
// 设置动画的播放时长
anim.duration = 3000
anim.start()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
setSelection(0)
}
}
}