CollapsingToolbarLayout - Dim/Blur the background image - android

I've got a collapsing toolbar with an imageview. When extended, it looks like this:
When collapsed, it looks like this:
I know that according to the guidelines, the toolbar should be of the primary color while collapsed, but i like the way i've set it up, and would like to keep it like that.
However, obviously, the toolbar title won't be visible if the image has a lot of white in it. So, is there a way i can blur/dim the background so that the toolbar title is visible at all times?
Edit: The image in question, is loaded from the internet using Picasso.

If you are using Picasso to display the image, then you can leverage the Transformation object in Picasso's builder and create a Blur effect class with something like this:
public class BlurEffect implements Transformation {
private static final int UP_LIMIT = 25;
private static final int LOW_LIMIT = 1;
protected final Context context;
private final int blurRadius;
public BlurEffect(Context context, int radius) {
this.context = context;
if (radius < LOW_LIMIT) {
this.blurRadius = LOW_LIMIT;
} else if (radius > UP_LIMIT) {
this.blurRadius = UP_LIMIT;
} else {
this.blurRadius = radius;
}
}
#Override public Bitmap transform(Bitmap source) {
Bitmap blurredBitmap;
blurredBitmap = Bitmap.createBitmap(source);
RenderScript renderScript = RenderScript.create(context);
Allocation input =
Allocation.createFromBitmap(renderScript, source,
Allocation.MipmapControl.MIPMAP_FULL,
Allocation.USAGE_SCRIPT);
Allocation output = Allocation.createTyped(renderScript, input.getType());
ScriptIntrinsicBlur script =
ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
script.setInput(input);
script.setRadius(blurRadius);
script.forEach(output);
output.copyTo(blurredBitmap);
return blurredBitmap;
}
#Override public String key() {
return "blurred";
}
}
Then you can use it from Picasso in this way, the more value in second parameter in the constructor, then blurer:
Picasso.with(appBarImage.getContext())
.load(track.getUrl())
.transform(new BlurEffect(this, 10))
.into(appBarImage);

My not optimal solution to this problem was to overlap two images, the normal and the blurred one, and change the alpha of the blurred one. When expanded, the alpha is 0. When collapsed its alpha is one. I used
AppBarLayout.addOnOffsetChangedListener
to get the scroll event. In my case
appBarLayout.addOnOffsetChangedListener((view, verticalOffset) -> {
if (mScrollRange == 0) {
mScrollRange = appBarLayout.getTotalScrollRange();
}
ViewCompat.setAlpha(mBlurredImage,
(float) (1 - Math.pow(((mScrollRange + verticalOffset) / (float) mScrollRange), 4)));
});
It is not ideal but it does its work

Ok, So, i just ended up using android:tint in the layout file in order to add a grayish tint to the image.For reference, the tint value i set is #55000000. This seems to make the title visible even on entirely white backgrounds.

You could use Blurry library
Blurry is an easy blur library for Android
// from Bitmap
Blurry.with(context).from(bitmap).into(imageView);
//use with Picasso
Blurry.with(MainActivity.this)
.radius(10)
.sampling(8)
.async()
.capture(findViewById(R.id.image_veiw))
.into((ImageView) findViewById(R.id.image_veiw));

You can use scrim for this. create gradient file in drawable folder.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="-90"
android:startColor="#00000000"
android:centerColor="#00000000"
android:endColor="#4d000000"
android:type="linear" />
</shape>
After creating the above file add an extra view to your layout like this
<FrameLayout>
<ImageView>
<View
android:background="#drawable/nameOfAboveFile"/>
<TexTView>
</FrameLayout>

Related

Android TransitionDrawable not fading

I have an ImageView and I am trying to fade from one image to the next using this code:
Drawable bgs[] = new Drawable[2];
public void redraw(int[][] grid) {
bgs[0] = bgs[1];
bgs[1] = new GameDrawable(grid, prefs.colors);
if (bgs[0] == null) {
gameField.setImageDrawable(bgs[1]);
} else {
TransitionDrawable crossfader = new TransitionDrawable(bgs);
crossfader.setCrossFadeEnabled(true);
gameField.setImageDrawable(crossfader);
crossfader.startTransition(500);
}
}
gameField is correctly referenced as an ImageView.
gameDrawable simply extends Drawable and draws the grid.
On each move and action the new GameDrawable is being rendered correctly but there is no fading whatsoever. The new image is simply displayed instantaneously. I have tried lengthening the transition time and swapping the order of the drawables with no effect.
Any help on is appreciated.
Update: I have now set my transition to something ridiculously long like 500000. The first drawable shows for a few seconds and then suddenly the second drawable appears. So still no transition.
Update 2:
I think my Drawable might be implemented incorrectly, so I have attached the code.
public class GameDrawable extends Drawable {
private Paint paint = new Paint();
private float blockWidth = 1;
private int[][] myGrid;
private int myColor;
private List<Point> myPoints;
public GameDrawable(int[][] grid) {
super();
this.myGrid = grid;
this.myColor = colors[yourColor];
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.FILL);
paint.setAlpha(0);
this.myPoints = yourPoints;
}
#Override
public void draw(Canvas canvas) {
float height = getBounds().height();
float width = getBounds().width();
blockWidth = width / myGrid.length;
if (height / myGrid.length < blockWidth) {
blockWidth = height / myGrid.length;
}
for (int x = 0; x < myGrid.length; x++) {
for (int y = 0; y < myGrid[x].length; y++) {
paint.setColor(colors[myGrid[x][y]]);
canvas.drawRect(x * blockWidth, y * blockWidth, (x+1)*blockWidth, (y+1)*blockWidth, paint);
}
}
}
#Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
invalidateSelf();
}
#Override
public void setColorFilter(ColorFilter cf) {
paint.setColorFilter(cf);
invalidateSelf();
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
Looking at your code, I see a problem at the line
bgs[0] = bgs[1];
bgs[1] has not yet been defined before this line and so bgs[0] is null for the first method call. Because of this, (bgs[0] == null) is true, and so the later defined bgs[1] is directly set to the gameField ImageView.
Use corrected code below.
Drawable bgs[] = new Drawable[2];
Drawable firstDrawable = getResources().getDrawable(R.drawable.transparent);
public void redraw(int[][] grid) {
bgs[0] = firstDrawable;
bgs[1] = new GameDrawable(grid, prefs.colors);
firstDrawable = bgs[1];
TransitionDrawable crossfader = new TransitionDrawable(bgs);
crossfader.setCrossFadeEnabled(true);
gameField.setImageDrawable(crossfader);
crossfader.startTransition(500);
}
Note that TransitionDrawable does not work properly when the Drawable sizes are different. So you may need to resize firstDrawable beforehand.
EXTRA: I would avoid setCrossFadeEnabled(true) since the whole TransitionDrawable becomes translucent during the transition, revealing the background. Sometimes, this creates a "blinking" effect and destroys the smoothness of the transition.
EDIT: Looking at your custom Drawable implementation, I think the problem lies in the line
canvas.drawColor(Color.WHITE);
in the draw() method.
I looked at TransitionDrawable.java source and found that setAlpha is called on the drawables to get the cross fade effect. However, your canvas has a solid white color and setAlpha() only affects the paint. Hope this is your answer.
EDIT 2: The actual problem, as pointed out by Michael, was that TransitionDrawable's setAlpha() calls on the Drawables were rendered ineffective due to paint.setColor() in the GameDrawable's draw() method overriding the paint's alpha value set by the TransitionDrawable.

where do u save a gif file in android eclipse? [duplicate]

I want to display animated GIF images in my aplication.
As I found out the hard way Android doesn't support animated GIF natively.
However it can display animations using AnimationDrawable:
Develop > Guides > Images & Graphics > Drawables Overview
The example uses animation saved as frames in application resources but what I need is to display animated gif directly.
My plan is to break animated GIF to frames and add each frame as drawable to AnimationDrawable.
Does anyone know how to extract frames from animated GIF and convert each of them into Drawable?
Android actually can decode and display animated GIFs, using android.graphics.Movie class.
This is not too much documented, but is in SDK Reference. Moreover, it is used in Samples in ApiDemos in BitmapDecode example with some animated flag.
UPDATE:
Use glide:
dependencies {
implementation 'com.github.bumptech.glide:glide:4.9.0'
}
usage:
Glide.with(context).load(GIF_URI).into(new DrawableImageViewTarget(IMAGE_VIEW));
see docs
also put (main/assets/htmls/name.gif) [with this html adjust to the size]
<html style="margin: 0;">
<body style="margin: 0;">
<img src="name.gif" style="width: 100%; height: 100%" />
</body>
</html>
declare in your Xml for example like this (main/res/layout/name.xml): [you define the size, for example]
<WebView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/webView"
android:layout_gravity="center_horizontal" />
in your Activity put the next code inside of onCreate
web = (WebView) findViewById(R.id.webView);
web.setBackgroundColor(Color.TRANSPARENT); //for gif without background
web.loadUrl("file:///android_asset/htmls/name.html");
if you want load dynamically you have to load the webview with data:
// or "[path]/name.gif" (e.g: file:///android_asset/name.gif for resources in asset folder), and in loadDataWithBaseURL(), you don't need to set base URL, on the other hand, it's similar to loadData() method.
String gifName = "name.gif";
String yourData = "<html style=\"margin: 0;\">\n" +
" <body style=\"margin: 0;\">\n" +
" <img src=" + gifName + " style=\"width: 100%; height: 100%\" />\n" +
" </body>\n" +
" </html>";
// Important to add this attribute to webView to get resource from outside.
webView.getSettings().setAllowFileAccess(true);
// Notice: should use loadDataWithBaseURL. BaseUrl could be the base url such as the path to asset folder, or SDCard or any other path, where your images or the other media resides related to your html
webView.loadDataWithBaseURL("file:///android_asset/", yourData, "text/html", "utf-8", null);
// Or if you want to load image from SD card or where else, here is the idea.
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
webView.loadDataWithBaseURL(base + '/', yourData, "text/html", "utf-8", null);
suggestion: is better load gif with static images for more information check https://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html
That's it, I hope you help.
Currently we can use Glide https://github.com/bumptech/glide
I solved the problem by splitting gif animations into frames before saving it to phone, so I would not have to deal with it in Android.
Then I download every frame onto phone, create Drawable from it and then create AnimationDrawable - very similar to example from my question
i found a very easy way, with a nice and simple working example here
display animated widget
Before getting it working there are some chages to do do in the code
IN THE FOLLOWING
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceStated);
setContentView(new MYGIFView());
}
}
just replace
setContentView(new MYGIFView());
in
setContentView(new MYGIFView(this));
AND IN
public GIFView(Context context) {
super(context);
Provide your own gif animation file
is = context.getResources().openRawResource(R.drawable.earth);
movie = Movie.decodeStream(is);
}
REPLACE THE FIRST LINE IN
public MYGIFView(Context context) {
according to the name of the class...
after done this little changes it should work as for me...
hope this help
Glide 4.6
1. To Load gif
GlideApp.with(context)
.load(R.raw.gif) // or url
.into(imageview);
2. To get the file object
GlideApp.with(context)
.asGif()
.load(R.raw.gif) //or url
.into(new SimpleTarget<GifDrawable>() {
#Override
public void onResourceReady(#NonNull GifDrawable resource, #Nullable Transition<? super GifDrawable> transition) {
resource.start();
//resource.setLoopCount(1);
imageView.setImageDrawable(resource);
}
});
Ways to show animated GIF on Android:
Movie class. As mentioned above, it's fairly buggy.
WebView. It's very simple to use and usually works. But sometimes it starts to misbehave, and it's always on some obscure devices you don't have. Plus, you can’t use multiple instances in any kind of list views, because it does things to your memory. Still, you might consider it as a primary approach.
Custom code to decode gifs into bitmaps and show them as Drawable or ImageView. I'll mention two libraries:
https://github.com/koral--/android-gif-drawable - decoder is implemented in C, so it's very efficient.
https://code.google.com/p/giffiledecoder - decoder is implemented in Java, so it's easier to work with. Still reasonably efficient, even with large files.
You'll also find many libraries based on GifDecoder class. That's also a Java-based decoder, but it works by loading the entire file into memory, so it's only applicable to small files.
I had a really hard time to have animated gif working in Android. I only had following two working:
WebView
Ion
WebView works OK and really easy, but the problem is it makes the view loads slower and the app would be unresponsive for a second or so. I did not like that. So I have tried different approaches (DID NOT WORK):
ImageViewEx is deprecated!
picasso did not load animated gif
android-gif-drawable looks great, but it caused some wired NDK issues in my project. It caused my local NDK library stop working, and I was not able to fix it
I had some back and forth with Ion; Finally, I have it working, and it is really fast :-)
Ion.with(imgView)
.error(R.drawable.default_image)
.animateGif(AnimateGifMode.ANIMATE)
.load("file:///android_asset/animated.gif");
Glide
Image Loader Library for Android, recommended by Google.
Glide is quite similar to Picasso but this is much faster than Picasso.
Glide consumes less memory than Picasso.
What that Glide has but Picasso doesn't
An ability to load GIF Animation to a simple ImageView might be the most interesting feature of Glide. And yes, you can't do that with Picasso.
Some important links-
https://github.com/bumptech/glide
http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
Use ImageViewEx, a library that makes using a gif as easy as using an ImageView.
Try this, bellow code display gif file in progressbar
loading_activity.xml(in Layout folder)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:indeterminate="true"
android:indeterminateDrawable="#drawable/custom_loading"
android:visibility="gone" />
</RelativeLayout>
custom_loading.xml(in drawable folder)
here i put black_gif.gif(in drawable folder), you can put your own gif here
<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#drawable/black_gif"
android:pivotX="50%"
android:pivotY="50%" />
LoadingActivity.java(in res folder)
public class LoadingActivity extends Activity {
ProgressBar bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
bar = (ProgressBar) findViewById(R.id.progressBar);
bar.setVisibility(View.VISIBLE);
}
}
Nobody has mentioned the Ion or Glide library. they work very well.
It's easier to handle compared to a WebView.
I have had success with the solution proposed within this article, a class called GifMovieView, which renders a View which can then be displayed or added to a specific ViewGroup. Check out the other methods presented in parts 2 and 3 of the specified article.
The only drawback to this method is that the antialiasing on the movie is not that good (must be a side-effect of using the "shady" Android Movie Class). You are then better off setting the background to a solid color within your animated GIF.
Some thoughts on the BitmapDecode example... Basically it uses the ancient, but rather featureless Movie class from android.graphics.
On recent API versions you need to turn off hardware acceleration, as described here. It was segfaulting for me otherwise.
<activity
android:hardwareAccelerated="false"
android:name="foo.GifActivity"
android:label="The state of computer animation 2014">
</activity>
Here is the BitmapDecode example shortened with only the GIF part. You have to make your own Widget (View) and draw it by yourself. Not quite as powerful as an ImageView.
import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.*;
import android.view.View;
public class GifActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GifView(this));
}
static class GifView extends View {
Movie movie;
GifView(Context context) {
super(context);
movie = Movie.decodeStream(
context.getResources().openRawResource(
R.drawable.some_gif));
}
#Override
protected void onDraw(Canvas canvas) {
if (movie != null) {
movie.setTime(
(int) SystemClock.uptimeMillis() % movie.duration());
movie.draw(canvas, 0, 0);
invalidate();
}
}
}
}
2 other methods, one with ImageView another with WebView can be found in this fine tutorial. The ImageView method uses the Apache licensed android-gifview from Google Code.
#PointerNull gave good solution, but it is not perfect. It doesn't work on some devices with big files and show buggy Gif animation with delta frames on pre ICS version.
I found solution without this bugs. It is library with native decoding to drawable: koral's android-gif-drawable.
For only android API (Android Pie)28 and + use AnimatedImageDrawable as
// ImageView from layout
val ima : ImageView = findViewById(R.id.img_gif)
// create AnimatedDrawable
val decodedAnimation = ImageDecoder.decodeDrawable(
// create ImageDecoder.Source object
ImageDecoder.createSource(resources, R.drawable.tenor))
// set the drawble as image source of ImageView
ima.setImageDrawable(decodedAnimation)
// play the animation
(decodedAnimation as? AnimatedImageDrawable)?.start()
XML code, add a ImageView
<ImageView
android:id="#+id/img_gif"
android:background="#drawable/ic_launcher_background" <!--Default background-->
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_width="200dp"
android:layout_height="200dp" />
AnimatedImageDrawable is a child of Drawable and created by ImageDecoder.decodeDrawable
ImageDecoder.decodeDrawable which further required the instance of ImageDecoder.Source created by ImageDecoder.createSource.
ImageDecoder.createSource can only take source as a name, ByteBuffer, File, resourceId, URI, ContentResolver to create source object and uses it to create AnimatedImageDrawable as Drawable (polymorphic call)
static ImageDecoder.Source createSource(AssetManager assets, String fileName)
static ImageDecoder.Source createSource(ByteBuffer buffer)
static ImageDecoder.Source createSource(File file)
static ImageDecoder.Source createSource(Resources res, int resId)
static ImageDecoder.Source createSource(ContentResolver cr, Uri uri)
Note: You can also create Bitmap using ImageDecoder#decodeBitmap.
Output:
AnimatedDrawable also supports resizing, frame and color manipulation
Put it into a WebView, it has to be able to display it correctly, since the default browser supports gif files. (Froyo+, if i am not mistaken)
There are two options to load animated gifs into our Android apps
1)Using Glide to load the gif into an ImageView.
String urlGif = "https://cdn.dribbble.com/users/263558/screenshots/1337078/dvsd.gif";
//add Glide implementation into the build.gradle file.
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Uri uri = Uri.parse(urlGif);
Glide.with(getApplicationContext()).load(uri).into(imageView);
2) Using an html to load the gif into a WebView
Create the html with the address to the .gif file:
<html style="margin: 0;">
<body style="margin: 0;">
<img src="https://..../myimage.gif" style="width: 100%; height: 100%" />
</body>
</html>
store this file into the assets directory:
The load this html into the WebView of your application:
WebView webView = (WebView)findViewById(R.id.webView);
webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("file:///android_asset/html/webpage_gif.html");
Heres is a complete example of this two options.
I think the better library to handle gif files is this one: by koral
Used it and i'm successful and this library is dedicated to GIF'S; but where as the picasso and glide are general purpose image framework; so i think the developers of this library have entirely concentrated on gif files
Use fresco. Here's how to do it:
http://frescolib.org/docs/animations.html
Here's the repo with the sample:
https://github.com/facebook/fresco/tree/master/samples/animation
Beware fresco does not support wrap content!
Just wanted to add that the Movie class is now deprecated.
This class was deprecated in API level P.
It is recommended to use this
AnimatedImageDrawable
Drawable for drawing animated images (like GIF).
Similar to what #Leonti said, but with a little more depth:
What I did to solve the same problem was open up GIMP, hide all layers except for one, export it as its own image, and then hide that layer and unhide the next one, etc., until I had individual resource files for each one. Then I could use them as frames in the AnimationDrawable XML file.
Something I did for showing gifs in apps. I extended ImageView so people can use its attributes freely. It can show gifs from url or from the assets directory.
The library also makes it easy for extending classes to inherit from it and extend it to support different methods to initialize the gif.
https://github.com/Gavras/GIFView
There's a little guide on the github page.
It was also published on Android Arsenal:
https://android-arsenal.com/details/1/4947
Use example:
From XML:
<com.whygraphics.gifview.gif.GIFView xmlns:gif_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_activity_gif_vie"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="center"
gif_view:gif_src="url:http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif" />
In the activity:
GIFView mGifView = (GIFView) findViewById(R.id.main_activity_gif_vie);
mGifView.setOnSettingGifListener(new GIFView.OnSettingGifListener() {
#Override
public void onSuccess(GIFView view, Exception e) {
Toast.makeText(MainActivity.this, "onSuccess()", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(GIFView view, Exception e) {
}
});
Setting the gif programmatically:
mGifView.setGifResource("asset:gif1");
Easiest way - Can be consider the below code
We can take advantage of Imageview setImageResource , refer below code for the same.
The below code can be used to show the image like gif incase if you have the multiple split image of gif. Just split the gif into individual png from a online tool and put image in the drawable like the below order
image_1.png, image_2.png, etc.
Have the handler to change the image dynamically.
int imagePosition = 1;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
updateImage();
}
};
public void updateImage() {
appInstance.runOnUiThread(new Runnable() {
#Override
public void run() {
int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", appInstance.getPackageName());
gifImageViewDummy.setImageResource(resId);
imagePosition++;
//Consider you have 30 image for the anim
if (imagePosition == 30) {
//this make animation play only once
handler.removeCallbacks(runnable);
} else {
//You can define your own time based on the animation
handler.postDelayed(runnable, 50);
}
//to make animation to continue use below code and remove above if else
// if (imagePosition == 30)
//imagePosition = 1;
// handler.postDelayed(runnable, 50);
//
}
});
}
The easy way to display animated GIF directly from URL to your app layout is to use WebView class.
Step 1:
In your layout XML
<WebView
android:id="#+id/webView"
android:layout_width="50dp"
android:layout_height="50dp"
/>
Step 2: In your Activity
WebView wb;
wb = (WebView) findViewById(R.id.webView);
wb.loadUrl("https://.......);
Step 3: In your Manifest.XML make Internet permission
<uses-permission android:name="android.permission.INTERNET" />
Step 4: In case you want to make your GIF background transparent and make GIF fit to your Layout
wb.setBackgroundColor(Color.TRANSPARENT);
wb.getSettings().setLoadWithOverviewMode(true);
wb.getSettings().setUseWideViewPort(true);
If you want to use Glide for loading gif:
Glide.with(this)
.asGif()
.load(R.raw.onboarding_layers) //Your gif resource
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.listener(new RequestListener<GifDrawable>() {
#Override
public boolean onLoadFailed(#Nullable #org.jetbrains.annotations.Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
resource.setLoopCount(1);
return false;
}
})
.into((ImageView) view.findViewById(R.id.layer_icons));
To save resources there is glide library for.
Have no idea why to use anything else, especialy webview to show image only.
Glide is perfect and easy library that prepares animated drawable from gif and put it directly to imageview.
The logic of gifdrawable handle animation itself.
Gif have lzw ziped raw rgb data of an animation inside.
There is no reason for complicated usage of webview and manage more files to show just a gif file in app.
First of all the Android browser should support Animated GIFs. If it doesn't then it's a bug! Have a look at the issue trackers.
If you're displaying these animated GIFs outside of a browser it might be a different story. To do what you're asking would require external library that supports the decoding of Animated GIFs.
The first port of call would be to look at Java2D or JAI (Java Advanced Imaging) API, although I would be very surprised if Android Dalvik would support those libraries in your App.
public class Test extends GraphicsActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private Bitmap mBitmap;
private Bitmap mBitmap2;
private Bitmap mBitmap3;
private Bitmap mBitmap4;
private Drawable mDrawable;
private Movie mMovie;
private long mMovieStart;
// Set to false to use decodeByteArray
private static final boolean DECODE_STREAM = true;
private static byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (java.io.IOException e) {
}
return os.toByteArray();
}
public SampleView(Context context) {
super(context);
setFocusable(true);
java.io.InputStream is;
is = context.getResources().openRawResource(R.drawable.icon);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm;
opts.inJustDecodeBounds = true;
bm = BitmapFactory.decodeStream(is, null, opts);
// now opts.outWidth and opts.outHeight are the dimension of the
// bitmap, even though bm is null
opts.inJustDecodeBounds = false; // this will request the bm
opts.inSampleSize = 4; // scaled down by 4
bm = BitmapFactory.decodeStream(is, null, opts);
mBitmap = bm;
// decode an image with transparency
is = context.getResources().openRawResource(R.drawable.icon);
mBitmap2 = BitmapFactory.decodeStream(is);
// create a deep copy of it using getPixels() into different configs
int w = mBitmap2.getWidth();
int h = mBitmap2.getHeight();
int[] pixels = new int[w * h];
mBitmap2.getPixels(pixels, 0, w, 0, 0, w, h);
mBitmap3 = Bitmap.createBitmap(pixels, 0, w, w, h,
Bitmap.Config.ARGB_8888);
mBitmap4 = Bitmap.createBitmap(pixels, 0, w, w, h,
Bitmap.Config.ARGB_4444);
mDrawable = context.getResources().getDrawable(R.drawable.icon);
mDrawable.setBounds(150, 20, 300, 100);
is = context.getResources().openRawResource(R.drawable.animated_gif);
if (DECODE_STREAM) {
mMovie = Movie.decodeStream(is);
} else {
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFCCCCCC);
Paint p = new Paint();
p.setAntiAlias(true);
canvas.drawBitmap(mBitmap, 10, 10, null);
canvas.drawBitmap(mBitmap2, 10, 170, null);
canvas.drawBitmap(mBitmap3, 110, 170, null);
canvas.drawBitmap(mBitmap4, 210, 170, null);
mDrawable.draw(canvas);
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int) ((now - mMovieStart) % dur);
mMovie.setTime(relTime);
mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight()
- mMovie.height());
invalidate();
}
}
}
}
class GraphicsActivity extends Activity {
// set to true to test Picture
private static final boolean TEST_PICTURE = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void setContentView(View view) {
if (TEST_PICTURE) {
ViewGroup vg = new PictureLayout(this);
vg.addView(view);
view = vg;
}
super.setContentView(view);
}
}
class PictureLayout extends ViewGroup {
private final Picture mPicture = new Picture();
public PictureLayout(Context context) {
super(context);
}
public PictureLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void addView(View child) {
if (getChildCount() > 1) {
throw new IllegalStateException(
"PictureLayout can host only one direct child");
}
super.addView(child);
}
#Override
public void addView(View child, int index) {
if (getChildCount() > 1) {
throw new IllegalStateException(
"PictureLayout can host only one direct child");
}
super.addView(child, index);
}
#Override
public void addView(View child, LayoutParams params) {
if (getChildCount() > 1) {
throw new IllegalStateException(
"PictureLayout can host only one direct child");
}
super.addView(child, params);
}
#Override
public void addView(View child, int index, LayoutParams params) {
if (getChildCount() > 1) {
throw new IllegalStateException(
"PictureLayout can host only one direct child");
}
super.addView(child, index, params);
}
#Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int count = getChildCount();
int maxHeight = 0;
int maxWidth = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
Drawable drawable = getBackground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
resolveSize(maxHeight, heightMeasureSpec));
}
private void drawPict(Canvas canvas, int x, int y, int w, int h, float sx,
float sy) {
canvas.save();
canvas.translate(x, y);
canvas.clipRect(0, 0, w, h);
canvas.scale(0.5f, 0.5f);
canvas.scale(sx, sy, w, h);
canvas.drawPicture(mPicture);
canvas.restore();
}
#Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
mPicture.endRecording();
int x = getWidth() / 2;
int y = getHeight() / 2;
if (false) {
canvas.drawPicture(mPicture);
} else {
drawPict(canvas, 0, 0, x, y, 1, 1);
drawPict(canvas, x, 0, x, y, -1, 1);
drawPict(canvas, 0, y, x, y, 1, -1);
drawPict(canvas, x, y, x, y, -1, -1);
}
}
#Override
public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
location[0] = getLeft();
location[1] = getTop();
dirty.set(0, 0, getWidth(), getHeight());
return getParent();
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = super.getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
}

How to remove white background color from BitmapDrawable or bitmap image in android?

I want to remove the white background color in a bitmap like in this example image.
This is my first try:
BitmapDrawable drawableImg = getImage();
drawableImg.setColorFilter(new PorterDuffColorFilter(Color.WHITE,
PorterDuff.Mode.DST_OUT));
Second try:
To remove the white colors range by setting fromBgColor and toBgColor, But when I replace the color with android transparent color the image turns into black here is the code:
public static Bitmap getBitmapWithTransparentBG(Bitmap srcBitmap,
int fromBgColor, int toBgColor) {
Bitmap result = srcBitmap.copy(Bitmap.Config.ARGB_8888, true);
int nWidth = result.getWidth();
int nHeight = result.getHeight();
for (int y = 0; y < nHeight; ++y)
for (int x = 0; x < nWidth; ++x) {
int nPixelColor = result.getPixel(x, y);
if (nPixelColor >= fromBgColor && nPixelColor <= toBgColor)
result.setPixel(x, y, Color.TRANSPARENT);
}
return result;
}
Hint I had a hint that bitmap does not support transparent bits and I should use PNG or Gif instead of bitmaps is that right?
Hint 2 It turned out that bitmap in Android has an option to show transparency since API level 1 using Bitmap.Config enum. Check this link in the documentation of Android.
what is beneath your image? Maybe it could be a layout issue. Have you tried setting android:background="#android:color/transparent" in the xml?
I see you tried the getBitmapWithTransparentBG described in
Android: Make specific (green) color in background image transparent
But have you tried also this?
How to change colors of a Drawable in Android?
About the image being jpg or png, I've managed to work with both after loading and setting it to a imageview (getting the bitmap back from it), and it allows to set the transparency using the getBitmapWithTransparentBG function as quoted above.

Using an Android Drawable as an AndEngine HUD

I'm trying to create an AndEngine HUD that will sit on top of a TMXTiledMap (bear with me, I'm very new to AndEngine). To keep things simple at first, I have a simple rectangle created via Android drawables. The idea is that this will sit at the bottom center of the screen and never move, even as the map underneath it is moved in various directions. For now, all I want to do is get that rectangle to show up. Later on I'll add other functionality to the rectangle.
My drawable is created like this:
?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners
android:radius="7dp" />
<gradient
android:startColor="#343434"
android:endColor="#17171717"
android:angle="270"
android:useLevel="false"
android:type="linear" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
And I have it pulled into a layout like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="300dip"
android:layout_height="100dip"
android:orientation="horizontal"
android:layout_marginLeft="20dp"
android:background="#drawable/menu_bkgrnd" >
</LinearLayout>
And then finally, here is where I try to pull it in as a HUD:
rect = new HUD();
ITouchArea container = (ITouchArea) findViewById(R.id.container);
this.rect.registerTouchArea(container);
rect.attachChild((IEntity) container);
As you can see, I'm doing a lot of casting to satisfy AndEngine, but when I run this, the map is totally screwed up. Am I going about this correctly? Is my casting incorrect? (or maybe both!).
Thanks for any help.
EDIT:
Based on the code that Jong and 正宗白布鞋 suggested below, I've adjusted my Java code as follows:
this.atlas = new BitmapTextureAtlas(null, 256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.atlas.load();
ITextureRegion drawable = BitmapTextureAtlasTextureRegionFactory.createFromResource(atlas, getApplicationContext(), R.drawable.myDrawable, 0, 0);
rect.attachChild(new Sprite(0, 0, drawable, this.getVertexBufferObjectManager()));
At this point, I'm still just trying to get this to appear on the screen. I'll adjust size and location later.
Everything compiles and runs without error, however my screen is just a total mess.
As you can see, I had to make a couple of small adjustments to the constructor arguments to get AndEngine to accept my instantiations. Not sure if I'm doing this correctly.
The other issue that I see in this code is that it appears to me that this code is just going to place an inactive shape on my screen. I know that in my original post, I said that my immediate goal is to make this rectangle show up, but I think that it has to show up as a registered touch area since it will ultimately be something with controls on it that need to respond to user commands. Sorry if I overly minimized what I am trying to do.
I'm still not getting this. Anybody have any suggestions? Thanks again!
You can't cast LinearLayout to ITouchArea, ITouchArea is an interface implemented by AndEngine classes only.
Like 正宗白布鞋 suggested, you should use the createFromResource method of BitmapTextureAtlasTextureRegionFactory.
You can use this code:
BitmapTextureAtlas atlas = new BitmapTextureAtlas(sizeX, sizeY, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
TextureRegion drawable = BitmapTextureAtlasTextureRegionFactory.createFromResource(atlas, getApplicationContext(), R.drawable.drawableId, 0, 0);
rect.attachChild(new Sprite(x, y, drawable));
EDIT:
If you want your sprite to respond to touch events, you can register it as a touch area in your rect HUD.
Sprite sprite = new Sprite(x, y, drawable, getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent pTouchEvent, final float pX, final float pY) {
//Do what you want here
}
}
rect.registerTouchArea(sprite);
rect.attachChild(sprite);
I had the same problem several days ago, and I couldn't find a proper answer. So now that I've gathered information from different sources, here is how I dealt with this.
AFAIK, it appears that the method createFromResource(atlas, getApplicationContext(), R.drawable.drawableId, 0, 0) from BitmapTextureAtlasTextureRegionFactory cannot deal with XML drawable (such as <shape>...</shape>).
Indeed, when I was only displaying a colored rectangle, everything was fine - and I think with a PNG file too -, but when I tried to create a Sprite from my XML drawable, I always got a NullBitmapException when the drawing happened.
Steps I took:
Convert drawable resource to Drawable
Convert Drawable to Bitmap (Source here)
Convert Bitmap to TextureRegion (This is where I used this)
Create a Sprite from the TextureRegion (or two for selected/unselected, like here)
Attach the Sprite to the game's HUD
So, with code:
Convert drawable resource TextureRegion
/**
* Takes a drawable, and converts it to a TextureRegion.
* #param context
* #param resId the drawable ID
* #param textureSizeX width for our TextureRegion
* #param textureSizeY height for our TextureRegion
* #return a TextureRegion from the drawable
*/
public static TextureRegion textureRegionFromDrawable(BaseGameActivity context, int resId, int textureSizeX, int textureSizeY) {
Drawable drawable = context.getResources().getDrawable(resId);
Bitmap bitmap = drawableToBitmap(drawable);
BitmapTextureAtlasTextureSource source = new BitmapTextureAtlasTextureSource(bitmap);
BitmapTextureAtlas textureAtlas = new BitmapTextureAtlas(context.getTextureManager(), textureSizeX, textureSizeY);
textureAtlas.addTextureAtlasSource(source, 0, 0);
textureAtlas.load();
TextureRegion textureRegion = (TextureRegion) TextureRegionFactory.createFromSource(textureAtlas, source, 0, 0);
return textureRegion;
}
// Drawable 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;
}
The utility intermediary class
public class BitmapTextureAtlasTextureSource extends BaseTextureAtlasSource implements IBitmapTextureAtlasSource {
private final int[] mColors;
public BitmapTextureAtlasTextureSource(Bitmap pBitmap) {
super(0, 0, pBitmap.getWidth(), pBitmap.getHeight());
mColors = new int[mTextureWidth * mTextureHeight];
for (int y = 0; y < mTextureHeight; ++y) {
for (int x = 0; x < mTextureWidth; ++x) {
mColors[x + y * mTextureWidth] = pBitmap.getPixel(x, y);
}
}
}
#Override
public Bitmap onLoadBitmap(Config pBitmapConfig) {
return Bitmap.createBitmap(mColors, mTextureWidth, mTextureHeight, Bitmap.Config.ARGB_8888);
}
#Override
public IBitmapTextureAtlasSource deepCopy() {
return new BitmapTextureAtlasTextureSource(Bitmap.createBitmap(mColors, mTextureWidth, mTextureHeight, Bitmap.Config.ARGB_8888));
}
#Override
public Bitmap onLoadBitmap(Config pBitmapConfig, boolean pMutable) {
// TODO Auto-generated method stub
return null;
}
}
Create two Sprite from the TextureRegions (I wanted 2 states for my button: selected/unselected), and attach them to the HUD
int textureSizeX = 512, textureSizeY = 512;
TextureRegion textureDefault = AndEngineUtils.textureRegionFromDrawable(activity, R.drawable.custom_menu_button, textureSizeX, textureSizeY);
TextureRegion textureSelected = AndEngineUtils.textureRegionFromDrawable(activity, R.drawable.custom_menu_button_selected, textureSizeX, textureSizeY);
mGameHUD = new HUD();
// 2 sprites for selected and unselected
final Sprite buttonUnselected, buttonSelected ;
buttonSelected = new Sprite(0, 0, textureSelected, activity.getVertexBufferObjectManager());
buttonSelected.setVisible(false);
buttonUnselected = new Sprite(0, 0, textureDefault, activity.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
switch (pSceneTouchEvent.getAction()) {
case TouchEvent.ACTION_DOWN:
// Change button
buttonSelected.setVisible(true);
this.setVisible(false);
break;
case TouchEvent.ACTION_UP:
// reset button
this.setVisible(true);
buttonSelected.setVisible(false);
break;
default:
break;
}
return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
}
};
mGameHUD.attachChild(buttonSelected);
mGameHUD.attachChild(buttonUnselected);
mGameHUD.registerTouchArea(buttonUnselected);
camera.setHUD(mGameHUD);
We can also make use of scene.setOnAreaTouchListener(touchListener) in order for an "unwanted" sliding gesture - until outside of the button - to take effet to reset the button color (see this thread).
I have just begun using AndEngine and I am not yet familiar with best practices, so feel free to correct me.

setColorFilter on ItemizedOverlay marker Drawable

I have a Drawable (a white circle) that I would like to colorize first, and then use it as a Marker in an ItemizedOverlay i.e. I'd like to use the same Drawable to show a green circle and an orange circle on the map.
Simply using setColorFilter on the drawable before calling ItemizedOverlay.setMarker() does not seem to work. I've also tried the mutable Bitmap approach detailed here -
setColorFilter doesn't work on Android < 2.2.
Both approaches simply draw the white circle with no color.
Can someone help me out? I'm running this on Android 2.2.
Thanks!
Update:
I adapted the code from How to change colors of a Drawable in Android? and got it to work for me.
My method looks like this:
private HashMap<Integer, Drawable> coloredPinCache = new HashMap<Integer, Drawable>();
public static final int ORIGINAL_PIN_COLOR = Color.WHITE;
public static final int COLOR_MATCH_THRESHOLD = 100;
protected Drawable getPinInColor(int color) {
// Check if we already have this in the cache
Drawable result = coloredPinCache.get(color);
// If not, create the Drawable
if (result == null) {
// load the original pin
Bitmap original = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
// create a mutable version of this
Bitmap mutable = original.copy(Bitmap.Config.ARGB_8888, true);
// garbage-collect the original pin, since it is not needed further
original.recycle();
original = null;
// loop through the entire image
// set the original color to whatever color we want
for(int x = 0;x < mutable.getWidth();x++){
for(int y = 0;y < mutable.getHeight();y++) {
if(match(mutable.getPixel(x, y), ORIGINAL_PIN_COLOR))
mutable.setPixel(x, y, color);
}
}
// create the Drawable from the modified bitmap
result = new BitmapDrawable(mutable);
// cache this drawable against its color
coloredPinCache.put(color, result);
}
// give back the colored drawable
return result;
}
private boolean match(int pixel, int color) {
return Math.abs(Color.red(pixel) - Color.red(color)) < COLOR_MATCH_THRESHOLD &&
Math.abs(Color.green(pixel) - Color.green(color)) < COLOR_MATCH_THRESHOLD &&
Math.abs(Color.blue(pixel) - Color.blue(color)) < COLOR_MATCH_THRESHOLD;
}
However, this approach is pretty resource-intensive. I'd still like to know if there's a better/faster/smarter way to accomplish this.
Thanks!

Categories

Resources