GifImageView.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * Copyright (c) 2020. BoostTag E.I.R.L. Romell D.Z.
  3. * All rights reserved
  4. * porfile.romellfudi.com
  5. */
  6. package com.romellfudi.ussdlibrary;
  7. import android.content.Context;
  8. import android.graphics.Canvas;
  9. import android.graphics.Movie;
  10. import android.net.Uri;
  11. import android.os.SystemClock;
  12. import android.util.AttributeSet;
  13. import android.util.Log;
  14. import android.view.View;
  15. import java.io.FileNotFoundException;
  16. import java.io.InputStream;
  17. public class GifImageView extends View {
  18. private InputStream mInputStream;
  19. private Movie mMovie;
  20. private int mWidth, mHeight;
  21. private long mStart;
  22. private Context mContext;
  23. public GifImageView(Context context) {
  24. super(context);
  25. this.mContext = context;
  26. }
  27. public GifImageView(Context context, AttributeSet attrs) {
  28. this(context, attrs, 0);
  29. }
  30. public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) {
  31. super(context, attrs, defStyleAttr);
  32. this.mContext = context;
  33. if (attrs.getAttributeName(1).equals("background")) {
  34. int id = Integer.parseInt(attrs.getAttributeValue(1).substring(1));
  35. setGifImageResource(id);
  36. }
  37. }
  38. private void init() {
  39. setFocusable(true);
  40. mMovie = Movie.decodeStream(mInputStream);
  41. mWidth = mMovie.width();
  42. mHeight = mMovie.height();
  43. requestLayout();
  44. }
  45. @Override
  46. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  47. setMeasuredDimension(mWidth, mHeight);
  48. }
  49. @Override
  50. protected void onDraw(Canvas canvas) {
  51. long now = SystemClock.uptimeMillis();
  52. if (mStart == 0) {
  53. mStart = now;
  54. }
  55. if (mMovie != null) {
  56. int duration = mMovie.duration();
  57. if (duration == 0) {
  58. duration = 1000;
  59. }
  60. int relTime = (int) ((now - mStart) % duration);
  61. mMovie.setTime(relTime);
  62. mMovie.draw(canvas, 0, 0);
  63. invalidate();
  64. }
  65. }
  66. public void setGifImageResource(int id) {
  67. mInputStream = mContext.getResources().openRawResource(id);
  68. init();
  69. }
  70. public void setGifImageUri(Uri uri) {
  71. try {
  72. mInputStream = mContext.getContentResolver().openInputStream(uri);
  73. init();
  74. } catch (FileNotFoundException e) {
  75. Log.e("GIfImageView", "File not found");
  76. }
  77. }
  78. }