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.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 ) 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 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;public class GifImage { public static class GifFrame { public Bitmap image; public int delay; public GifFrame (Bitmap im, int del) { image = im; delay = del; } } 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; protected int height; protected boolean gctFlag; protected int gctSize; protected int loopCount = 1 ; protected int [] gct; protected int [] lct; protected int [] act; protected int bgIndex; protected int bgColor; protected int lastBgColor; protected int pixelAspect; protected boolean lctFlag; protected boolean interlace; protected int lctSize; protected int ix, iy, iw, ih; protected int lrx, lry, lrw, lrh; protected Bitmap image; protected Bitmap lastImage; 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 ]; protected int blockSize = 0 ; protected int dispose = 0 ; protected int lastDispose = 0 ; protected boolean transparency = false ; protected int delay = 0 ; protected int transIndex; protected static final int MaxStackSize = 4096 ; protected short [] prefix; protected byte [] suffix; protected byte [] pixelStack; protected byte [] pixels; protected Vector<GifFrame> frames; protected int frameCount; public int getWidth () { return width; } public int getHeigh () { return height; } 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]; if (lastDispose > 0 ) { if (lastDispose == 3 ) { 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); if (lastDispose == 2 ) { 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; } } } } } 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; int dlim = dx + iw; if ((k + width) < dlim) { dlim = k + width; } int sx = i * iw; while (dx < dlim) { 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; } 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]; } if (prefix == null ) { prefix = new short [MaxStackSize]; } if (suffix == null ) { suffix = new byte [MaxStackSize]; } if (pixelStack == null ) { pixelStack = new byte [MaxStackSize + 1 ]; } 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; } datum = bits = count = first = top = pi = bi = 0 ; for (i = 0 ; i < npix;) { if (top == 0 ) { if (bits < code_size) { if (count == 0 ) { count = readBlock(); if (count <= 0 ) { break ; } bi = 0 ; } datum += (((int ) block[bi]) & 0xff ) << bits; bits += 8 ; bi++; count--; continue ; } code = datum & code_mask; datum >>= code_size; bits -= code_size; if ((code > available) || (code == end_of_information)) { break ; } if (code == clear) { 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 ; 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; } top--; pixels[pi++] = pixelStack[top]; i++; } for (i = pi; i < npix; i++) { pixels[i] = 0 ; } } protected boolean err () { return status != STATUS_OK; } 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; } 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 ]; 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; } protected void readContents () { boolean done = false ; while (!(done || err())) { int code = read(); switch (code) { case 0x2C : readImage(); break ; case 0x21 : code = read(); switch (code) { case 0xf9 : readGraphicControlExt(); break ; case 0xff : readBlock(); String app = "" ; for (int i = 0 ; i < 11 ; i++) { app += (char ) block[i]; } if (app.equals("NETSCAPE2.0" )) { readNetscapeExt(); } else { skip(); } break ; default : skip(); } break ; case 0x3b : done = true ; break ; case 0x00 : break ; default : status = STATUS_FORMAT_ERROR; } } } protected void readGraphicControlExt () { read(); int packed = read(); dispose = (packed & 0x1c ) >> 2 ; if (dispose == 0 ) { dispose = 1 ; } transparency = (packed & 1 ) != 0 ; delay = readShort() * 10 ; transIndex = read(); read(); } 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 () { ix = readShort(); iy = readShort(); iw = readShort(); ih = readShort(); int packed = read(); lctFlag = (packed & 0x80 ) != 0 ; interlace = (packed & 0x40 ) != 0 ; lctSize = 2 << (packed & 7 ); if (lctFlag) { lct = readColorTable(lctSize); act = lct; } else { act = gct; if (bgIndex == transIndex) { bgColor = 0 ; } } int save = 0 ; if (transparency) { save = act[transIndex]; act[transIndex] = 0 ; } if (act == null ) { status = STATUS_FORMAT_ERROR; } if (err()) { return ; } decodeImageData(); skip(); if (err()) { return ; } frameCount++; image = Bitmap.createBitmap(width, height, Config.RGB_565); setPixels(); frames.addElement(new GifFrame(image, delay)); if (transparency) { act[transIndex] = save; } resetFrame(); } protected void readLSD () { width = readShort(); height = readShort(); int packed = read(); gctFlag = (packed & 0x80 ) != 0 ; gctSize = 2 << (packed & 7 ); bgIndex = read(); pixelAspect = read(); } protected void readNetscapeExt () { do { readBlock(); if (block[0 ] == 1 ) { int b1 = ((int ) block[1 ]) & 0xff ; int b2 = ((int ) block[2 ]) & 0xff ; loopCount = (b2 << 8 ) | b1; } } while ((blockSize > 0 ) && !err()); } protected int readShort () { 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 ; } 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 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 { 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 { 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 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个方法:
onAnimationStart:在动画开始时触发。
onAnimationEnd:在动画结束时触发。
onAnimationRepeat:在动画重播时触发。
与帧动画一样,补间动画也需要找一个宿主视图,对宿主视图施展动画效果;不同的是,帧动画的宿主视图只能是由ImageView派生出来的视图家族(图像视图、图像按钮等),而补间动画的宿主视图可以是任意视图,只要派生自View类就行 。
给补间动画指定宿主视图的方式很简单,调用宿主对象的startAnimation 方法即可命令宿主视图开始播放动画 ,调用宿主对象的clearAnimation 方法即可要求宿主视图清除动画 。
补间动画初始化方式 初始化灰度动画 在构造方法中指定视图透明度的前后数值,取值为0.0~1.0(0表示完全不透明,1表示完全透明)。
1 2 val alphaAnim = AlphaAnimation(1f ,0.1f )
初始化平移动画 在构造方法中指定视图在平移前后左上角的坐标值 。其中,第一个参数为平移前的横坐标,第二个参数为平移后的横坐标,第三个参数为平移前的纵坐标,第四个参数为平移后的纵坐标。
1 2 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 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.uiimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport android.view.animation.AlphaAnimationimport android.view.animation.Animationimport android.view.animation.Animation.AnimationListenerimport android.view.animation.RotateAnimationimport android.view.animation.ScaleAnimationimport android.view.animation.TranslateAnimationimport android.widget.AdapterViewimport android.widget.AdapterView.OnItemSelectedListenerimport android.widget.ArrayAdapterimport com.study.animationstudy.Rimport com.study.animationstudy.base.BaseActivityimport com.study.animationstudy.databinding.ActivityTweenAnimBindingimport com.study.animationstudy.util.Utilsclass 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() initTweenSpinner() } fun initTweenAnim () { alphaAnim = AlphaAnimation(1f ,0.1f ) alphaAnim.duration = 3000 alphaAnim.fillAfter = true 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 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 -> { 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 -> { 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 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的处理大同小异,对中间状态的视图变换处理不外乎以下两个步骤:
根据插值时间计算当前的状态值(如灰度、平移距离、缩放比率、旋转角度等)。
在宿主视图上使用该状态值执行变换操作。
例如:钟摆的左右摆动,这个摆动操作其实由3段旋转动画构成。
以上面的端点为圆心,钟摆以垂直向下的状态向左旋转,转到左边的某个角度停住(比如左转60度)。
钟摆从左边向右边旋转,转到右边的某个角度停住(比如右转120度,与垂直方向的夹角为60度)。
钟摆从右边再向左旋转,当其摆到垂直方向时完成一个周期的摇摆动作。
根据插值时间计算对应的角度,具体到代码实现上需要做以下两处调整:
旋转动画初始化时只有两个度数,即起始角度和终止角度。摇摆动画需要3个参数,即中间角度(既是起始角度也是终止角度)、摆到左侧的角度和摆到右侧的角度。
根据插值时间估算当前所处的角度。对于摇摆动画来说,需要做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 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 () { val alphaAnimation = AlphaAnimation(1f ,0.1f ) alphaAnimation.duration = 3000 alphaAnimation.fillAfter = true 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 ){ val alphaAnimation = AlphaAnimation(0.1f ,1f ) alphaAnimation.duration = 3000 alphaAnimation.fillAfter = true 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 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个方法。
onAnimationStart:在动画开始播放时触发。
onAnimationEnd:在动画结束播放时触发。
onAnimationCancel:在动画取消播放时触发。
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 <*>?) { } } } } 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的组装方法说明。
with:指定该动画与当前动画一起播放。
before:指定该动画在当前动画之前播放。
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) 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 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 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() } 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 ?) { } }
利用估值器实现弹幕动画
定义一个间距估值器,实现接口TypeEvaluator的evaluate方法,并在该方法中返回指定时间点的间距数值。
调用ValueAnimator类的ofObject方法,根据间距估值器、开始位置和结束位置构建属性动画对象。
调用属性动画对象的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 } 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 } 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 ; 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 ) } } }