android


How to properly create a customized animated drawable?


Background
I've been searching in plenty of places to find out how to animate a drawable without animating the view and without using the built in drawables.
The reason is that I will need to prepare a customized animation within the drawable, and I might have different requirements for it later.
For now, I'm making a basic animated drawable that just spins a given bitmap inside it.
I've set it on an imageView, but I wish to be able to use it on any kind of view, even customized views that have overridden the onDraw function.
The problem
I can't find out how to show the drawable without being cut, no matter what the size of the view is. Here's what I see:
The code
Here's the code:
private class CircularAnimatedDrawable extends Drawable implements Animatable {
private static final Interpolator ANGLE_INTERPOLATOR = new LinearInterpolator();
private static final int ANGLE_ANIMATOR_DURATION = 2000;
private final RectF fBounds = new RectF();
private float angle = 0;
private ObjectAnimator mObjectAnimatorAngle;
private final Paint mPaint;
private boolean mRunning;
private final Bitmap mBitmap;
public CircularAnimatedDrawable(final Bitmap bitmap) {
this.mBitmap = bitmap;
mPaint = new Paint();
setupAnimations();
}
public float getAngle() {
return this.angle;
}
public void setAngle(final float angle) {
this.angle = angle;
invalidateSelf();
}
#Override
public Callback getCallback() {
return mCallback;
}
#Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle);
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
canvas.restore();
}
#Override
public void setAlpha(final int alpha) {
mPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(final ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
#Override
protected void onBoundsChange(final Rect bounds) {
super.onBoundsChange(bounds);
fBounds.left = bounds.left;
fBounds.right = bounds.right;
fBounds.top = bounds.top;
fBounds.bottom = bounds.bottom;
}
private void setupAnimations() {
mObjectAnimatorAngle = ObjectAnimator.ofFloat(this, "angle", 360f);
mObjectAnimatorAngle.setInterpolator(ANGLE_INTERPOLATOR);
mObjectAnimatorAngle.setDuration(ANGLE_ANIMATOR_DURATION);
mObjectAnimatorAngle.setRepeatMode(ValueAnimator.RESTART);
mObjectAnimatorAngle.setRepeatCount(ValueAnimator.INFINITE);
}
#Override
public void start() {
if (isRunning())
return;
mRunning = true;
mObjectAnimatorAngle.start();
invalidateSelf();
}
#Override
public void stop() {
if (!isRunning())
return;
mRunning = false;
mObjectAnimatorAngle.cancel();
invalidateSelf();
}
#Override
public boolean isRunning() {
return mRunning;
}
}
and the usage :
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.spinner_76_inner_holo);
final CircularAnimatedDrawable circularAnimatedDrawable = new CircularAnimatedDrawable(bitmap);
circularAnimatedDrawable.setCallback(imageView);
circularAnimatedDrawable.start();
imageView.setImageDrawable(circularAnimatedDrawable);
The question
How can I set it to make the drawable fit the view?
Should I use the bitmap size? the fBounds? both? Or maybe something else?
try this modified version of your Drawable:
class CircularAnimatedDrawable extends Drawable implements Animatable, TimeAnimator.TimeListener {
private static final float TURNS_PER_SECOND = 0.5f;
private Bitmap mBitmap;
private boolean mRunning;
private TimeAnimator mTimeAnimator = new TimeAnimator();
private Paint mPaint = new Paint();
private Matrix mMatrix = new Matrix();
public CircularAnimatedDrawable(final Bitmap bitmap) {
mBitmap = bitmap;
mTimeAnimator.setTimeListener(this);
}
#Override
public void draw(final Canvas canvas) {
canvas.drawBitmap(mBitmap, mMatrix, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
Log.d(TAG, "onBoundsChange " + bounds);
mMatrix.setRectToRect(new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight()),
new RectF(bounds),
Matrix.ScaleToFit.CENTER);
}
#Override
public void onTimeUpdate(TimeAnimator animation, long totalTime, long deltaTime) {
Rect b = getBounds();
mMatrix.postRotate(360 * TURNS_PER_SECOND * deltaTime / 1000, b.centerX(), b.centerY());
invalidateSelf();
}
#Override
public void setAlpha(final int alpha) {
mPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(final ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
#Override
public void start() {
if (isRunning())
return;
mRunning = true;
mTimeAnimator.start();
invalidateSelf();
}
#Override
public void stop() {
if (!isRunning())
return;
mRunning = false;
mTimeAnimator.cancel();
invalidateSelf();
}
#Override
public boolean isRunning() {
return mRunning;
}
}
EDIT: version without Animator stuff (uses [un]scheduleSelf), NOTE it uses View's Drawable.Callback mechanism so it usually cannot be started directly from onCreate where View doesn't have attached Handler yet
class CircularAnimatedDrawable extends Drawable implements Animatable, Runnable {
private static final float TURNS_PER_SECOND = 0.5f;
private static final long DELAY = 50;
private Bitmap mBitmap;
private long mLastTime;
private boolean mRunning;
private Paint mPaint = new Paint();
private Matrix mMatrix = new Matrix();
public CircularAnimatedDrawable(final Bitmap bitmap) {
mBitmap = bitmap;
}
#Override
public void draw(final Canvas canvas) {
canvas.drawBitmap(mBitmap, mMatrix, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
Log.d(TAG, "onBoundsChange " + bounds);
mMatrix.setRectToRect(new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight()),
new RectF(bounds),
Matrix.ScaleToFit.CENTER);
}
#Override
public void setAlpha(final int alpha) {
mPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(final ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
#Override
public void start() {
if (isRunning())
return;
mRunning = true;
mLastTime = SystemClock.uptimeMillis();
scheduleSelf(this, 0);
invalidateSelf();
}
#Override
public void stop() {
if (!isRunning())
return;
mRunning = false;
unscheduleSelf(this);
invalidateSelf();
}
#Override
public boolean isRunning() {
return mRunning;
}
#Override
public void run() {
long now = SystemClock.uptimeMillis();
Rect b = getBounds();
long deltaTime = now - mLastTime;
mLastTime = now;
mMatrix.postRotate(360 * TURNS_PER_SECOND * deltaTime / 1000, b.centerX(), b.centerY());
scheduleSelf(this, now + DELAY);
invalidateSelf();
}
}
ok, the fix is:
#Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, fBounds.width() / 2 + fBounds.left, fBounds.height() / 2 + fBounds.top);
canvas.translate(fBounds.left, fBounds.top);
canvas.drawBitmap(mBitmap, null, new Rect(0, 0, (int) fBounds.width(), (int) fBounds.height()), mPaint);
canvas.restore();
}
#Override
public int getIntrinsicHeight() {
return mBitmap.getHeight();
}
#Override
public int getIntrinsicWidth() {
return mBitmap.getWidth();
}
It works fine. I hope it will be enough for the future changes.
EDIT: here's an optimization to the above, including all changes:
class CircularAnimatedDrawable extends Drawable implements Animatable {
private static final Interpolator ANGLE_INTERPOLATOR = new LinearInterpolator();
private static final int ANGLE_ANIMATOR_DURATION = 2000;
private float angle = 0;
private ObjectAnimator mObjectAnimatorAngle;
private final Paint mPaint;
private boolean mRunning;
private final Bitmap mBitmap;
private final Matrix mMatrix = new Matrix();
public CircularAnimatedDrawable(final Bitmap bitmap) {
this.mBitmap = bitmap;
mPaint = new Paint();
mPaint.setAntiAlias(true);
setupAnimations();
}
#SuppressWarnings("unused")
public float getAngle() {
return this.angle;
}
#SuppressWarnings("unused")
public void setAngle(final float angle) {
this.angle = angle;
invalidateSelf();
}
#Override
public void draw(final Canvas canvas) {
final Rect b = getBounds();
canvas.save();
canvas.rotate(angle, b.centerX(), b.centerY());
canvas.drawBitmap(mBitmap, mMatrix, mPaint);
canvas.restore();
}
#Override
public void setAlpha(final int alpha) {
mPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(final ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
#Override
protected void onBoundsChange(final Rect bounds) {
super.onBoundsChange(bounds);
mMatrix.setRectToRect(new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight()), new RectF(bounds),
Matrix.ScaleToFit.CENTER);
}
#Override
public int getIntrinsicHeight() {
return mBitmap.getHeight();
}
#Override
public int getIntrinsicWidth() {
return mBitmap.getWidth();
}
private void setupAnimations() {
mObjectAnimatorAngle = ObjectAnimator.ofFloat(this, "angle", 360f);
mObjectAnimatorAngle.setInterpolator(ANGLE_INTERPOLATOR);
mObjectAnimatorAngle.setDuration(ANGLE_ANIMATOR_DURATION);
mObjectAnimatorAngle.setRepeatMode(ValueAnimator.RESTART);
mObjectAnimatorAngle.setRepeatCount(ValueAnimator.INFINITE);
}
#Override
public void start() {
if (isRunning())
return;
mRunning = true;
mObjectAnimatorAngle.start();
invalidateSelf();
}
#Override
public void stop() {
if (!isRunning())
return;
mRunning = false;
mObjectAnimatorAngle.cancel();
invalidateSelf();
}
#Override
public boolean isRunning() {
return mRunning;
}
}

Related Links

Google In app test product consumption
How to start time with progress from where it stopped in android?
Inflate view with new child above all existing children
I want to Close Navigation Drawer if and only if I click the Button
Most efficient way to search in a table
Resize JavaCV Frame in Android
want to add design library in app
Fragment Not opening with FragmentPagerAdapter
I tried to add compile 'com.github.bumptech.glide:glide:3.7.0' in app.gradle
FirebaseListAdapter<Model.Class>
Navigation drawer not navigating to the fragment from MainAcvtivity
Not able to open “Project Structure” in Android studio
Airplane mode simulation on a real Android device with calabash-android
simplecursoradapter listview filtering with toolbar searchview example
Is GSON performing safe serialization?
How to insert RecycleView between Viewpager and its Fragments?

Categories

HOME
service-worker
sonarqube
phantom-dsl
twitter-bootstrap-3
visual-studio-emulator
hugo
regular-language
jquery-ui
owin
ibeacon-android
enthought
heap
redis-sentinel
ycsb
filechannel
google-form
gkturnbasedmatch
comsol
parameter-passing
digital-signature
cfml
imagemap
question2answer
dynamically-generated
fat
custom-post-type
firebase-analytics
clickjacking
least-squares
imx6
sharepoint-workflow
hivemq
release
bc
verifiable-c
loading
google-data-api
mcustomscrollbar
plaintext
angular-http
apache-directory
httrack
builder
term
yii2-api
launchctl
convex-optimization
remedy
payara-micro
aquamacs
video-conferencing
subnet
seq
rsa-archer-grc
reachability
choice
visual-studio-2008-sp1
pacemaker
mta
rspec2
dimension
data-protection
lz77
grass
httpruntime.cache
toast
user-management
inf
java-money
dllimport
video-player
jsvc
snoop
telepat
fail2ban
shopizer
actionfilterattribute
gamekit
variadic-templates
iiop
sql-scripts
psr-4
rmysql
angular-carousel
parallel-testing
ray
jquery-slider
file-not-found
android-usb
script#
time.h
resource-management
booksleeve
xcode3.2
rmiregistry
fitbounds
inline-formset
unattended-processing
collectionviewsource
squishit
object-database
drupal-fivestar
echo3
web-application-project
alsb
java1.4

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App