Related
I am working on a android launcher that shows the 1st 4 app icons in a grid view however I'm trying to display the folder as a square shape it's showing up as a circle shape...
heres my code:
package appname.launcher.util;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import Appname.launcher.activity.Home;
public class GroupIconDrawable extends Drawable{
private int outlinepad;
Bitmap[] icons;
public int iconSize;
Paint paint;
Paint paint2;
Paint paint4;
private int iconSizeDiv2;
private int padding;
private float scaleFactor = 1;
private boolean needAnimate,needAnimatScale;
public View v;
private float sx = 1;
private float sy = 1 ;
public GroupIconDrawable(Bitmap[] icons,int size){
init(icons,size);
}
private void init(Bitmap[] icons,int size){
this.icons = icons;
this.iconSize = size;
iconSizeDiv2 = Math.round(iconSize / 2f);
padding = iconSize /25;
this.paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAlpha(200);
paint.setAntiAlias(true);
this.paint4 = new Paint();
paint4.setColor(Color.WHITE);
paint4.setAntiAlias(true);
paint4.setFlags(Paint.ANTI_ALIAS_FLAG);
paint4.setStyle(Paint.Style.STROKE);
outlinepad = Tools.convertDpToPixel(2, Home.desktop.getContext());
paint4.setStrokeWidth(outlinepad);
this.paint2 = new Paint();
paint2.setAntiAlias(true);
paint2.setFilterBitmap(true);
}
public GroupIconDrawable(Bitmap[] icons,int size,View v){
init(icons,size);
this.v =v;
}
public void popUp(){
sy = 1;
sx = 1;
needAnimate = true;
needAnimatScale = true;
invalidateSelf();
}
public void popBack(){
needAnimate = false;
needAnimatScale = false;
invalidateSelf();
}
#Override
public void draw(Canvas canvas) {
canvas.save();
if (needAnimatScale){
scaleFactor = Tools.clampFloat(scaleFactor-0.09f,0.5f,1f);
}else {
scaleFactor = Tools.clampFloat(scaleFactor+0.09f,0.5f,1f);
}
if (v == null)
canvas.scale(scaleFactor,scaleFactor,iconSize/2,iconSize/2);
else
canvas.scale(scaleFactor,scaleFactor,iconSize/2,v.getHeight() / 2);
if (v!= null)
canvas.translate(0,v.getHeight()/2-iconSize/2);
Path clipp = new Path();
clipp.addCircle(iconSize / 2,iconSize / 2,iconSize / 2-outlinepad, Path.Direction.CW);
canvas.clipPath(clipp, Region.Op.REPLACE);
canvas.drawBitmap(icons[0],null,new Rect(padding,padding, iconSizeDiv2-padding, iconSizeDiv2-padding),paint2);
canvas.drawBitmap(icons[1],null,new Rect(iconSizeDiv2+padding,padding,iconSize-padding, iconSizeDiv2-padding),paint2);
canvas.drawBitmap(icons[2],null,new Rect(padding, iconSizeDiv2+padding, iconSizeDiv2-padding,iconSize-padding),paint2);
canvas.drawBitmap(icons[3],null,new Rect(iconSizeDiv2+padding, iconSizeDiv2+padding,iconSize-padding,iconSize-padding),paint2);
canvas.clipRect(0,0,iconSize,iconSize, Region.Op.REPLACE);
canvas.restore();
if (needAnimate){
paint2.setAlpha(Tools.clampInt(paint2.getAlpha()-25,0,255));
invalidateSelf();
}else if (paint2.getAlpha() != 255){
paint2.setAlpha(Tools.clampInt(paint2.getAlpha()+25,0,255));
invalidateSelf();
}
}
#Override
public void setAlpha(int i) {}
#Override
public void setColorFilter(ColorFilter colorFilter) {}
#Override
public int getOpacity() {return 0;}
}
I think its because of the > clipp.addCircle(iconSize / 2,iconSize /
2,iconSize / 2-outlinepad,> Path.Direction.CW); code but i'm not sure
how would I make it a square instead of a circle?
change your clipp Path usage from addCircle to be addRect(float left, float top, float right, float bottom, Path.Direction dir)
I am setting a layer list to an imageview with drawable programatically in android
My custom Drawable is as follows,
package cl.tk.ui.iBAPView;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import cl.tk.R;
public class CircleDrawable extends Drawable {
private int color;
private boolean checked = false;
private int size;
private Paint paint= new Paint(Paint.DITHER_FLAG);
private Context context;
public CircleDrawable(Context context,boolean checked,int color,int size) {
this.checked=checked;
this.color=color;
this.size=size;
this.context=context;
}
#Override
public void draw(Canvas canvas) {
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(size/ 2, size / 2,size / 2, paint);
if (checked)
drawChecked(canvas);
}
private void drawChecked(Canvas canvas) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_check);
float posX = (canvas.getWidth() - bitmap.getWidth()) / 2;
float posY = (canvas.getHeight() - bitmap.getHeight()) / 2;
canvas.drawBitmap(bitmap, posX, posY, paint);
}
#Override
public void setAlpha(int alpha) {
// do nothing
}
#Override
public void setColorFilter(ColorFilter cf) {
// do nothing
}
#Override
public int getOpacity() {
return PixelFormat.UNKNOWN;
}
}
This is my code to create layer list drawable and set it to imageview,
public static void setChecked_Selector(Context context,ImageView view) {
try {
int size= (int) context.getResources().getDimension(R.dimen._17sdp);
/* Drawable pressed=squareView(ContextCompat.getColor(context,R.color.colorBlue),ContextCompat.getColor(context,R.color.colorRed),size);//new BadgeDrawable(context,colorPressed);
Drawable normal=squareView(ContextCompat.getColor(context,R.color.colorwhite),ContextCompat.getColor(context,R.color.colorRed),size);*/
Drawable pressed=new CircleDrawable(context,true,ContextCompat.getColor(context,R.color.colorGreen),size);
Drawable normal=new CircleDrawable(context,false,ContextCompat.getColor(context,R.color.colorGray),size);
Drawable[] drawarray = {pressed, normal};
LayerDrawable layerdrawable = new LayerDrawable(drawarray);
view.setBackgroundDrawable(layerdrawable);
view.setImageLevel(0);
view.setTag(0);
} catch (Exception e) {
}
}
and on click of imageview, i am trying to change the drawable but failed as the condition is working perfectly but layerlist drawable is not changing,
My code on click listener of imageView,
case R.id.ah_img_agree:
{
int imageLevel=-1;
if(0==(int)v.getTag())
imageLevel=1;
else
imageLevel=0;
((ImageView)v).setImageLevel(imageLevel);
rbAgreed.setTag(imageLevel);
}
break;
I follow this example [here][1] to to give circuler shape. I am getting images from server and set it via BaseAdapter, the image is showing but not in circular view. So, can anyone tell what is the mistake with my code, following is the way I load the images and set circular shape
aQuery.id(holder.propic).image(listData.get(position).get(INTEREST_ACCEPT_IMG),true,true,0,R.drawable.ic_launcher);
Bitmap icon = BitmapFactory.decodeFile(listData.get(position).get(INTEREST_ACCEPT_IMG));
holder.propic.setImageBitmap(icon);
Use this link for library to get circular image view
https://github.com/hdodenhof/CircleImageView
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CircleImageView extends ImageView {
private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private static final int COLORDRAWABLE_DIMENSION = 2;
private static final int DEFAULT_BORDER_WIDTH = 0;
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
private static final boolean DEFAULT_BORDER_OVERLAY = false;
private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF();
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint();
private int mBorderColor = DEFAULT_BORDER_COLOR;
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight;
private float mDrawableRadius;
private float mBorderRadius;
private ColorFilter mColorFilter;
private boolean mReady;
private boolean mSetupPending;
private boolean mBorderOverlay;
public CircleImageView(Context context) {
super(context);
init();
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);
mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR);
mBorderOverlay = a.getBoolean(R.styleable.CircleImageView_border_overlay, DEFAULT_BORDER_OVERLAY);
a.recycle();
init();
}
private void init() {
super.setScaleType(SCALE_TYPE);
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
#Override
public ScaleType getScaleType() {
return SCALE_TYPE;
}
#Override
public void setScaleType(ScaleType scaleType) {
if (scaleType != SCALE_TYPE) {
throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
}
}
#Override
public void setAdjustViewBounds(boolean adjustViewBounds) {
if (adjustViewBounds) {
throw new IllegalArgumentException("adjustViewBounds not supported.");
}
}
#Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) {
return;
}
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
if (mBorderWidth != 0) {
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
}
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setup();
}
public int getBorderColor() {
return mBorderColor;
}
public void setBorderColor(int borderColor) {
if (borderColor == mBorderColor) {
return;
}
mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
public void setBorderColorResource(#ColorRes int borderColorRes) {
setBorderColor(getContext().getResources().getColor(borderColorRes));
}
public int getBorderWidth() {
return mBorderWidth;
}
public void setBorderWidth(int borderWidth) {
if (borderWidth == mBorderWidth) {
return;
}
mBorderWidth = borderWidth;
setup();
}
public boolean isBorderOverlay() {
return mBorderOverlay;
}
public void setBorderOverlay(boolean borderOverlay) {
if (borderOverlay == mBorderOverlay) {
return;
}
mBorderOverlay = borderOverlay;
setup();
}
#Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
}
#Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
mBitmap = getBitmapFromDrawable(drawable);
setup();
}
#Override
public void setImageResource(#DrawableRes int resId) {
super.setImageResource(resId);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
}
#Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
}
#Override
public void setColorFilter(ColorFilter cf) {
if (cf == mColorFilter) {
return;
}
mColorFilter = cf;
mBitmapPaint.setColorFilter(mColorFilter);
invalidate();
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap
.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError e) {
return null;
}
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
mDrawableRect.set(mBorderRect);
if (!mBorderOverlay) {
mDrawableRect.inset(mBorderWidth, mBorderWidth);
}
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
invalidate();
}
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
}
And use it in your containt_activity.xml like this:
<com.example.customewidget.CircleImageView
android:id="#+id/imgUserImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/no_image_available"
app:border_color="#color/white"
app:border_width="1dp" />
Add in you Activity or Fragment class:
public class ImageActivity extends Activity {
private CircleImageView imgUserImage;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.containt_activity);
imgUserImage = (CircleImageView) view.findViewById(R.id.imgUserImage);
//here set your image view
}
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;
}
}
am creating an app in which people can draw a sketch and save to the gallery. This I have done and is working fine. What I would like to be able to do is take an image from the Gallery and be able to draw on that. I have been able to bring up the Gallery to pick the image but I haven't been able to work out how to imbed that image onto the canvas to then draw on
but the prob is , it opens up the gallery...but when i click on any pic to open up, it just goes back to app, but not with the picture, without the picture ( my screen stays same as before, no new picture) ...so what's the problem?
My Mainactivity class---
package com.example.drawingfun;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.UUID;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
private DrawingView drawView;
private ImageButton currPaint,drawBtn,eraseBtn, newBtn,saveBtn,gal;
private float smallBrush, mediumBrush,largeBrush;
int GALLERY_INTENT_CALLED = 3; // has to be a unique request code
Drawable image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawView = (DrawingView)findViewById(R.id.drawing);
LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
currPaint = (ImageButton)paintLayout.getChildAt(0);
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
smallBrush = getResources().getInteger(R.integer.small_size);
mediumBrush = getResources().getInteger(R.integer.medium_size);
largeBrush = getResources().getInteger(R.integer.large_size);
drawBtn = (ImageButton)findViewById(R.id.draw_btn);
drawBtn.setOnClickListener(this);
drawView.setBrushSize(mediumBrush);
eraseBtn = (ImageButton)findViewById(R.id.erase_btn);
eraseBtn.setOnClickListener(this);
newBtn = (ImageButton)findViewById(R.id.new_btn);
newBtn.setOnClickListener(this);
saveBtn = (ImageButton)findViewById(R.id.save_btn);
saveBtn.setOnClickListener(this);
gal = (ImageButton)findViewById(R.id.GalleryButton);
gal.setOnClickListener(this);
}
public void paintClicked(View view){
drawView.setErase(false);
drawView.setBrushSize(drawView.getLastBrushSize());
//use chosen color
if(view!=currPaint){
//update color
ImageButton imgView = (ImageButton)view;
String color = view.getTag().toString();
drawView.setColor(color);
imgView.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint));
currPaint=(ImageButton)view;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View view){
//respond to clicks
if(view.getId()==R.id.draw_btn){
//draw button clicked
final Dialog brushDialog = new Dialog(this);
brushDialog.setTitle("Brush size:");
brushDialog.setContentView(R.layout.brush_chooser);
ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_brush);
smallBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setErase(false);
drawView.setBrushSize(smallBrush);
drawView.setLastBrushSize(smallBrush);
brushDialog.dismiss();
}
});
ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_brush);
mediumBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setErase(false);
drawView.setBrushSize(mediumBrush);
drawView.setLastBrushSize(mediumBrush);
brushDialog.dismiss();
}
});
ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_brush);
largeBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setErase(false);
drawView.setBrushSize(largeBrush);
drawView.setLastBrushSize(largeBrush);
brushDialog.dismiss();
}
});
brushDialog.show();
}
else if(view.getId()==R.id.erase_btn){
//switch to erase - choose size
final Dialog brushDialog = new Dialog(this);
brushDialog.setTitle("Eraser size:");
brushDialog.setContentView(R.layout.brush_chooser);
ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_brush);
smallBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setErase(true);
drawView.setBrushSize(smallBrush);
brushDialog.dismiss();
}
});
ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_brush);
mediumBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setErase(true);
drawView.setBrushSize(mediumBrush);
brushDialog.dismiss();
}
});
ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_brush);
largeBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setErase(true);
drawView.setBrushSize(largeBrush);
brushDialog.dismiss();
}
});
brushDialog.show();
}
else if(view.getId()==R.id.new_btn){
//new button
AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
newDialog.setTitle("New drawing");
newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
drawView.startNew();
dialog.dismiss();
}
});
newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
newDialog.show();
}
else if(view.getId()==R.id.save_btn){
//save drawing
AlertDialog.Builder saveDialog = new AlertDialog.Builder(this);
saveDialog.setTitle("Save drawing");
saveDialog.setMessage("Save drawing to device Gallery?");
saveDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
//save drawing
drawView.setDrawingCacheEnabled(true);
//attempt to save
String imgSaved = MediaStore.Images.Media.insertImage(
getContentResolver(), drawView.getDrawingCache(),
UUID.randomUUID().toString()+".png", "drawing");
//feedback
if(imgSaved!=null){
Toast savedToast = Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery!", Toast.LENGTH_SHORT);
savedToast.show();
}
else{
Toast unsavedToast = Toast.makeText(getApplicationContext(),
"Oops! Image could not be saved.", Toast.LENGTH_SHORT);
unsavedToast.show();
}
drawView.destroyDrawingCache();
}
});
saveDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
saveDialog.show();
}
else if(view.getId()==R.id.GalleryButton){
//new button
AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
newDialog.setTitle("New drawing");
newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Intent choosePictureIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, 101);
}
});
newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
newDialog.show();
}
}
public void setDrawingThemefrmGallery()
{
Intent pickPhoto = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, GALLERY_INTENT_CALLED);
}
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent returnedIntent) {
drawView.drawImage(drawableToBitmap(image));
super.onActivityResult(requestCode, resultCode, returnedIntent);
if (requestCode == GALLERY_INTENT_CALLED) {
if (resultCode == RESULT_OK) {
try {
Uri selectedImage = returnedIntent.getData();
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
image = Drawable.createFromStream(inputStream, selectedImage.toString());
} catch (FileNotFoundException e) {}
}
}
}
}
My DrawingView class---
package com.example.drawingfun;
import java.io.File;
import android.view.View;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.view.MotionEvent;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
public class DrawingView extends View {
//drawing path
private Path drawPath;
//drawing and canvas paint
private Paint drawPaint, canvasPaint;
//initial color
private int paintColor = 0xFF660000;
//canvas
private Canvas drawCanvas;
//canvas bitmap
private Bitmap canvasBitmap;
private float brushSize, lastBrushSize;
private boolean erase=false;
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
setupDrawing();
// TODO Auto-generated constructor stub
}
private void setupDrawing() {
// TODO Auto-generated method stub
brushSize = getResources().getInteger(R.integer.medium_size);
lastBrushSize = brushSize;
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(brushSize);
drawPaint.setStyle(Paint.Style.FILL_AND_STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
//view given size
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
//draw view
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//detect user touch
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
public void setColor(String newColor){
//set color
invalidate();
if(newColor.startsWith("#")){
paintColor = Color.parseColor(newColor);
drawPaint.setColor(paintColor);
drawPaint.setShader(null);
}
else{
//pattern
int patternID = getResources().getIdentifier(
newColor, "drawable", "com.example.drawingfun");
//decode
Bitmap patternBMP = BitmapFactory.decodeResource(getResources(), patternID);
//create shader
BitmapShader patternBMPshader = new BitmapShader(patternBMP,
Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
//color and shader
drawPaint.setColor(0xFFFFFFFF);
drawPaint.setShader(patternBMPshader);
}
}
public void setBrushSize(float newSize){
//update size
float pixelAmount = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
newSize, getResources().getDisplayMetrics());
brushSize=pixelAmount;
drawPaint.setStrokeWidth(brushSize);
}
public void setLastBrushSize(float lastSize){
lastBrushSize=lastSize;
}
public float getLastBrushSize(){
return lastBrushSize;
}
public void setErase(boolean isErase){
//set erase true or false
erase=isErase;
if(erase)
{
paintColor = Color.parseColor("WHITE");
drawPaint.setColor(paintColor);
//drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
drawPaint.setShader(null);
}
else
drawPaint.setXfermode(null);
}
public void startNew(){
drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
invalidate();
}
public void drawImage(Bitmap image) {
drawCanvas.drawBitmap(image, 0, 0, canvasPaint);
invalidate();
}
}
You need to load images as Bitmaps and then draw them using a Canvas object.
refer to this question to learn how to convert a drawable to a Bitmap.
And follow this example:
public class DrawView extends View{
private Paint bufferPaint;
private Bitmap buffer;
private Canvas board;
private Path currPath;
public DrawView(Context context) {
super(context);
bufferPaint = new Paint(Paint.DITHER_FLAG);
}
public void init() {
buffer = Bitmap.createBitmap(getWidth(), getHeight(),
Bitmap.Config.ARGB_8888);
board = new Canvas(buffer);
invalidate();
}
public void drawBitmap(Bitmap bitmap) {
board.drawBitmap(bitmap, 0, 0, bufferPaint)
}
#Override
public void onDraw(Canvas canvas) {
if (buffer != null) {
canvas.drawBitmap(buffer, 0, 0, bufferPaint);
}
}
}
the drawBitmap method does the trick. now you can use the canvas object (board) to draw other stuff on your Bitmap.
Define these globally
int GALLERY_INTENT_CALLED = 3; // has to be a unique request code
Drawable image;
Get image from user using this code
Intent pickPhoto = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, GALLERY_INTENT_CALLED);
Then in your activity's onActivityResult, get the image
protected void onActivityResult(int requestCode, int resultCode,
Intent returnedIntent) {
super.onActivityResult(requestCode, resultCode, returnedIntent);
if (requestCode == CAMERA_INTENT_CALLED) {
if (resultCode == RESULT_OK) {
try {
Uri selectedImage = returnedIntent.getData()
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
image = Drawable.createFromStream(inputStream, selectedImage.toString());
} catch (FileNotFoundException e) {}
}
}
}
in DrawingView write this method
public void drawImage(Bitmap image) {
drawCanvas.drawBitmap(image, 0, 0, canvasPaint);
invalidate();
}
use the method from this post to convert image to Bitmap:
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
then whenever in Mainactivity you wanna draw the image call
drawView.drawImage(drawableToBitmap(image))