How to Animate object in android while - android

Is there a way to for a Bitmap object to have a transparent background instead of solid color.. I'd like my background image (set on XML layout to show)?
sadly, none of the other question worked for me, otherwise, I wouldn't be asking... THANKS IN ADVANCE! ALSO, any tips on how to get the animation to work with XML?
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
public class Vehicle extends View{
Bitmap vehicle;
int x_axisMovement;
public Vehicle(Context context) {
super(context);
// TODO Auto-generated constructor stub
vehicle = BitmapFactory.decodeResource(getResources(), R.drawable.vehicle_bus);
x_axisMovement = 1024;
}
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.drawColor(Color.TRANSPARENT); // NOT WORKING
canvas.drawBitmap(vehicle, x_axisMovement, 400, null);
if(x_axisMovement > -256){
x_axisMovement -= 4;
}
else
{
x_axisMovement = 1024;
}
invalidate();
}
}

You can use it in xml and add it in a relative layout so youll have a view on top of another view
sample:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher" >
<com.example.Vehicle
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Now com.example is the folder inside your src folder but you might have different folder just press ctrl+shift+o so it will automatically give you an hint to the class location.
Now your class
public class Vehicle extends View {
Bitmap vehicle;
int x_axisMovement;
public Vehicle(Context context) {
super(context);
init();
}
public Vehicle(Context context, AttributeSet s) {
super(context, s);
init();
}
public Vehicle(Context context, AttributeSet s, int style) {
super(context, s, style);
init();
}
public void init() {
vehicle = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
x_axisMovement = 1024;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.TRANSPARENT); // NOT WORKING
canvas.drawBitmap(vehicle, x_axisMovement, 400, null);
if (x_axisMovement > -256) {
x_axisMovement -= 4;
} else {
x_axisMovement = 1024;
}
invalidate();
}
}
You need to have that 3 constructor to enable the class to be used in an xml form.
now the result:
The background is the big ic_launcher and the image from your class in the small ic_launcher.

Related

How to capture part of a ScrollView as its content is scrolling?

After extending the ScrollView class I was able to easily be notified of the scrolling in realtime.
Now I need to capture the content of this scrollview in a very specific part.
Let's say I want to capture the top of the screen (matching parent width and a defined height, like 100dp). But only the content of the ScrollView and not the rest, if there is anything else on the top but not as part of the ScrollView.
I tried using on the scrollview :
setDrawingCacheEnabled(true);
getDrawingCache(true);
setDrawingCacheEnabled(false);
Then I tried to crop so that I get the part I want :
Bitmap.createBitmap(complete, 0, 0, width, height);
Results are very far from what I want to achieve and performance are very very poor and at some point I would get either a SIGENV or getDrawingCache(true) tries to use a recycled bitmap...
So how can I easily capture the content in the desired area without too much performance hit ?
Note: this process must be done as I am scrolling the content, so inside ScrollView's onScrollChanged(final int x, final int y).
Thanks !
Since the problem was fun I implemented it, it seems to work fine. I guess that you are recreating a Bitmap each time that's why goes slow.
The idea is like this, you create an area in the ScrollView that you want to copy (see Rect cropRect and Bitmap screenshotBitmap), it's full width and you just need to set the height. The view automatically set a scroll listener on itself and on every scroll it will copy that area. Note that setDrawingCacheEanbled(true) is called just once when the view is instantiated, it basically tells the view that you will call getDrawingCache(), which will return the Bitmap on which the view is drawing itself. It then copy the area of interest on screenshotBitmap and that's the Bitmap that you might want to use.
ScreenshottableScrollView.java
package com.example.lelloman.screenshottablescrollview;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.ScrollView;
/**
* Created by lelloman on 16-2-16.
*/
public class ScreenshottableScrollView extends ScrollView implements ViewTreeObserver.OnScrollChangedListener {
public interface OnNewScreenshotListener {
void onNewScreenshot(Bitmap bitmap);
}
private Bitmap screenshotBitmap = null;
private Canvas screenshotCanvas = null;
private int screenshotHeightPx = 0;
private OnNewScreenshotListener listener = null;
private Rect cropRect;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public ScreenshottableScrollView(Context context) {
super(context);
init();
}
public ScreenshottableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ScreenshottableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ScreenshottableScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init(){
setDrawingCacheEnabled(true);
getViewTreeObserver().addOnScrollChangedListener(this);
}
public void setOnNewScreenshotListener(OnNewScreenshotListener listener){
this.listener = listener;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if(screenshotHeightPx != 0)
makeScrenshotBitmap(w,h);
}
public void setScreenshotHeightPx(int q){
screenshotHeightPx = q;
makeScrenshotBitmap(getWidth(), getHeight());
}
private void makeScrenshotBitmap(int width, int height){
if(screenshotBitmap != null) screenshotBitmap.recycle();
if(width == 0 || height == 0) return;
screenshotBitmap = Bitmap.createBitmap(width, screenshotHeightPx, Bitmap.Config.ARGB_8888);
screenshotCanvas = new Canvas(screenshotBitmap);
cropRect = new Rect(0,0,width,screenshotHeightPx);
}
#Override
public void onScrollChanged() {
if(listener == null) return;
Bitmap bitmap = getDrawingCache();
screenshotCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
screenshotCanvas.drawBitmap(bitmap,cropRect, cropRect,paint);
listener.onNewScreenshot(screenshotBitmap);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.lelloman.screenshottablescrollview.MainActivity">
<com.example.lelloman.screenshottablescrollview.ScreenshottableScrollView
android:id="#+id/scrollView"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.example.lelloman.screenshottablescrollview.ScreenshottableScrollView>
<View
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#ff000000"/>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="100dp" />
</LinearLayout>
MainActivity.java
package com.example.lelloman.screenshottablescrollview;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StringBuilder builder = new StringBuilder();
Random random = new Random();
String AB = "abcdefghijklmnopqrstuvwxyz ";
for(int i=0;i<100;i++){
builder.append("\n\n"+Integer.toString(i)+"\n\n");
for(int j =0;j<1000;j++){
builder.append(AB.charAt(random.nextInt(AB.length())));
}
}
((TextView) findViewById(R.id.textView)).setText(builder.toString());
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
ScreenshottableScrollView scrollView = (ScreenshottableScrollView) findViewById(R.id.scrollView);
scrollView.setScreenshotHeightPx((int) (getResources().getDisplayMetrics().density * 100));
scrollView.setOnNewScreenshotListener(new ScreenshottableScrollView.OnNewScreenshotListener() {
#Override
public void onNewScreenshot(Bitmap bitmap) {
Log.d("MainActivity","onNewScreenshot");
imageView.setImageBitmap(bitmap);
}
});
}
}

android - custom view has width and height of 0

I'm trying to create a custom view with two TextViews inside a vertical LinearLayout, but am totally confused as to how it all works.
Currently nothing is appearing as I my onDraw method isn't being called. I think this is due to the fact that my view (the LinearLayout?) has a width and height of both 0.
I think I should be overwriting my onMeasure, but after trying setMeasuredDimension(100,100) this still isn't working.
I am trying to inflate an xml inside the view and use the two TextViews in that.
An explanation would also be great so I can hopefully get my head around how this all works.
Thanks
size_button.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/sizeButtonSizeText"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:id="#+id/sizeButtonSlugText"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
SizeButton.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View.MeasureSpec;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.nap.library.NapApplication;
import com.nap.library.R;
public class SizeButton extends LinearLayout {
private TextView mSize;
private TextView mSlug;
private String mSizeText;
private String mSlugText;
private Paint mPaint;
private boolean mSoldOut;
private Context mContext;
/*
public SizeButton(Context context) {
super(context);
setup();
}
public SizeButton(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
*/
public SizeButton(Context context, String size, String slug) {
super(context);
mContext = context;
mSizeText = size;
mSlugText = slug;
setup();
}
public void setSoldOut(){
this.mSoldOut = true;
}
public boolean isSoldOut(){
return mSoldOut;
}
public void setSizeText(String size){
mSize.setText(size);
}
public void setSlugText(String slug){
mSlug.setText(slug);
}
public void setup(){
mPaint = new Paint();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout buttonLayout = (LinearLayout) inflater.inflate(R.layout.size_button, null);
mSize = (TextView) buttonLayout.findViewById(R.id.sizeButtonSizeText);
mSize.setGravity(Gravity.CENTER);
mSize.setTextColor(Color.BLACK);
mSize.setText(mSizeText);
mSize.setTypeface(NapApplication.mPorter);
mSize.setWidth(10);
mSlug = (TextView) buttonLayout.findViewById(R.id.sizeButtonSlugText);
mSlug.setGravity(Gravity.CENTER);
mSlug.setTextColor(Color.BLACK);
mSlug.setText(mSlugText);
mSlug.setTypeface(NapApplication.mPorter);
invalidate();
requestLayout();
LinearLayout.LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
mSize.setLayoutParams(layoutParams);
mSlug.setLayoutParams(layoutParams);
Log.i("button","in setup");
Log.i("button","width = "+this.getWidth()+" height = "+this.getHeight());
Log.i("button","width = "+mSize.getWidth()+" sizeheight = "+mSize.getHeight());
Log.i("button","width = "+mSlug.getWidth()+" slugheight = "+mSlug.getHeight());
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.i("button","in onMeasure");
setMeasuredDimension(100,100);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i("button","in ondraw");
}
}
ProductFragment.java - where the button is added to the fragment
for (int i = 0; i < mItem.getSizes().length; i++) {
final SizeButton sizeButton = new SizeButton(getActivity(),mItem.getSizes()[i],"hello");
// Each size button has a sku set as its tag
sizeButton.setTag(mItem.getSkus()[i]);
sizeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mItem.getSizes().length > 1) {
boolean selected = !sizeButton.isSelected();
if (selected) {
mCurrentSku = (String) v.getTag();
} else {
mCurrentSku = null;
}
}
configureButtons();
}
});
Log.e("button","Adding button to view");
mSizesWrapper.addView(sizeButton);
}
As your are extending a ViewGroup, you should override dispatchDraw(), not onDraw()

How to play GIF in android

Hello stackoverflow I'm trying to develop an android application to play my own GIF, here is the code snippet
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
AnimationView.java
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.view.View;
public class AnimationView extends View {
private Movie mMovie;
private long mMovieStart;
private static final boolean DECODE_STREAM = true;
private int mDrawLeftPos;
private int mHeight, mWidth;
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 AnimationView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
java.io.InputStream is;
is = context.getResources().openRawResource(R.drawable.scanning);
if (DECODE_STREAM) {
mMovie = Movie.decodeStream(is);
} else {
byte[] array = streamToBytes(is);
mMovie = Movie.decodeByteArray(array, 0, array.length);
}
}
#Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec )
{
int p_top = this.getPaddingTop(), p_bottom = this.getPaddingBottom();
mWidth = mMovie.width();
mHeight = mMovie.height();
// Calculate new desired height
final int desiredHSpec = MeasureSpec.makeMeasureSpec( mHeight + p_top + p_bottom , MeasureSpec.EXACTLY );
setMeasuredDimension( widthMeasureSpec, desiredHSpec );
super.onMeasure( widthMeasureSpec, desiredHSpec );
// Update the draw left position
mDrawLeftPos = Math.max( ( this.getWidth() - mWidth ) / 2, 0) ;
}
#Override
public void onDraw(Canvas 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 = 3000;
}
int relTime = (int) ((now - mMovieStart) % dur);
// Log.d("", "real time :: " +relTime);
mMovie.setTime(relTime);
mMovie.draw(canvas, mDrawLeftPos, this.getPaddingTop());
invalidate();
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<com.example.androidgifwork.AnimationView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</LinearLayout>
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidgifwork"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.example.androidgifwork.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
When I run the above code snippet GIF is not at all running, but when I remove android:targetSdkVersion="19" GIF running, please help me to solve this riddle.
Thanks
2017 UPDATED ANSWER
To play GIF in android use Glide library to load any image or GIF.
Glide.with(context)
.load(YOUR_GIF)
.into(YOUR_IMAGE_VIEW);
Use Glide to load normal images, images from server or even to load GIF as well. Also have a look at Picasso android image loading library which is similar to Glide but as of now(16 Apr 2017) Picasso doesn't support GIF loading in android yet.
######################################################################
OLD ANSWER
For all Those who want to play GIF in your app please find the code below
PlayGifView.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
public class PlayGifView extends View{
private static final int DEFAULT_MOVIEW_DURATION = 1000;
private int mMovieResourceId;
private Movie mMovie;
private long mMovieStart = 0;
private int mCurrentAnimationTime = 0;
#SuppressLint("NewApi")
public PlayGifView(Context context, AttributeSet attrs) {
super(context, attrs);
/**
* Starting from HONEYCOMB have to turn off HardWare acceleration to draw
* Movie on Canvas.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
public void setImageResource(int mvId){
this.mMovieResourceId = mvId;
mMovie = Movie.decodeStream(getResources().openRawResource(mMovieResourceId));
requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(mMovie != null){
setMeasuredDimension(mMovie.width(), mMovie.height());
}else{
setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight());
}
}
#Override
protected void onDraw(Canvas canvas) {
if (mMovie != null){
updateAnimtionTime();
drawGif(canvas);
invalidate();
}else{
drawGif(canvas);
}
}
private void updateAnimtionTime() {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) {
mMovieStart = now;
}
int dur = mMovie.duration();
if (dur == 0) {
dur = DEFAULT_MOVIEW_DURATION;
}
mCurrentAnimationTime = (int) ((now - mMovieStart) % dur);
}
private void drawGif(Canvas canvas) {
mMovie.setTime(mCurrentAnimationTime);
mMovie.draw(canvas, 0, 0);
canvas.restore();
}
}
In your activity class use the following code to play GIF
PlayGifView pGif = (PlayGifView) findViewById(R.id.viewGif);
pGif.setImageResource(<Your GIF file name Eg: R.drawable.infinity_gif>);
XML layout
<yourPacckageName.PlayGifView
android:id="#+id/viewGif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
Use Glide to load any gif from your project's raw folder or external URL into ImageView, ImageButtons or similar [Glide targets][2]
Glide.with(getActivity()).load(R.raw.alarm).asGif().into(btnAlert);
If you can use a WebView, GIFs will play directly over it. But I am not sure, in your case whether you want to put it in a Webview or not.
add this to your dependencies (build.gradle)
allprojects {
repositories {
mavenCentral()
}
}
dependencies {
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.15'
}
and use this in xml to show your gif
<pl.droidsonroids.gif.GifTextView
android:id="#+id/gifTextView2"
android:layout_width="230dp"
android:layout_height="200dp"
android:layout_weight="1"
android:src="#drawable/dev_option_gif"
/>
More info at: https://github.com/koral--/android-gif-drawable
Android provides the class android.graphics.Movie. This class is capable of decoding and playing InputStreams. So for this approach, we create a class GifMovieView and let it inherit from View a detailed tutorial is given at http://droid-blog.net/2011/10/14/tutorial-how-to-use-animated-gifs-in-android-part-1/
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUZy1BVlZSbExvYUU
** android:hardwareAccelerated="false" in Manifest File**
package com.keshav.gifimageexampleworking;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity
{
private GifImageView gifImageView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gifImageView = (GifImageView) findViewById(R.id.GifImageView);
gifImageView.setGifImageResource(R.drawable.success1);
}
#Override
protected void onResume()
{
super.onResume();
//refresh long-time task in background thread
new Thread(new Runnable() {
#Override
public void run() {
try {
//dummy delay for 2 second
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//update ui on UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
gifImageView.setGifImageResource(R.drawable.success);
}
});
}
}).start();
}
}
package com.keshav.gifimageexampleworking;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.net.Uri;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class GifImageView extends View {
private InputStream mInputStream;
private Movie mMovie;
private int mWidth, mHeight;
private long mStart;
private Context mContext;
public GifImageView(Context context) {
super(context);
this.mContext = context;
}
public GifImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GifImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
if (attrs.getAttributeName(1).equals("background")) {
int id = Integer.parseInt(attrs.getAttributeValue(1).substring(1));
setGifImageResource(id);
}
}
private void init() {
setFocusable(true);
mMovie = Movie.decodeStream(mInputStream);
mWidth = mMovie.width();
mHeight = mMovie.height();
requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(mWidth, mHeight);
}
#Override
protected void onDraw(Canvas canvas) {
long now = SystemClock.uptimeMillis();
if (mStart == 0) {
mStart = now;
}
if (mMovie != null) {
int duration = mMovie.duration();
if (duration == 0) {
duration = 1000;
}
int relTime = (int) ((now - mStart) % duration);
mMovie.setTime(relTime);
mMovie.draw(canvas, 10, 10);
invalidate();
}
}
public void setGifImageResource(int id) {
mInputStream = mContext.getResources().openRawResource(id);
init();
}
public void setGifImageUri(Uri uri) {
try {
mInputStream = mContext.getContentResolver().openInputStream(uri);
init();
} catch (FileNotFoundException e) {
Log.e("GIfImageView", "File not found");
}
}
}
For devices running API 29(Pie) & above you can use AnimatedImageDrawable to play GIF(s) and WebP animated images.
Here's a sample:
ImageView imgGif = findViewById(R.id.imgGif);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
try {
drawable = ImageDecoder.decodeDrawable(ImageDecoder.createSource(getResources(), R.drawable.giphy));
imgGif.setImageDrawable(drawable);
if (drawable instanceof AnimatedImageDrawable) {
((AnimatedImageDrawable) drawable).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Using this provides more control & features you can use on the image such as:
Checking whether the gif is running
Starting & stopping the playback.
Applying color filters
Changing image shape
and much more
You can also use Coil library, which gives you a bit less control over Gif images than Glide does. But still gives simple implementation if you just want to load the GIF once and show. Probably, if you want to repeat that you need to trigger the drawable again or just call the load function once again. Anyway even if calling load again the resources should be cached under the hood(something to be investigated, not 100% sure).
Everything you need is adding dependency:
implementation "io.coil-kt:coil-gif:1.0.0"
And specifying your decoding mechanism:
val imageLoader = ImageLoader.Builder(context)
.componentRegistry {
if (SDK_INT >= 28) {
add(ImageDecoderDecoder())
} else {
add(GifDecoder())
}
}
.build()
That's all go-ahead and load images/gifs directly in your image views:
app_logo.load("needed_gif_url")
Don't forget to pass the needed image loader to each request where you need your decoder to be used, as for GIFs. Or just make your custom imageLoader as default for each request:
Coil.setImageLoader(imageLoader)
Animated GIFs in Android is a difficult topic. It is an issue that has been discussed heavily and still, it is very difficult for developers to bring GIFs to life. using glide and pl.droidsonroids.gif:android-gif-drawable made some problem to build gradle. so I found a method that not using any dependencies.I used this method to load the gif in my views:
GifAnimView.java:
package com.app.samplegif;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.graphics.Paint;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import com.app.samplegif.R;
import java.io.IOException;
import java.io.InputStream;
#SuppressLint("NewApi")
public class GifAnimView extends View {
private Context _context;
private Movie gifMovie;
private String gifName = "not set";
private InputStream gifStream;
private int width;
private int height;
private long startTime;
private Paint paint;
public GifAnimView(Context context, AttributeSet attrs) {
super(context,attrs);
initGif(context,attrs);
_context = context;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (gifStream == null || gifMovie == null) {
canvas.drawColor(Color.WHITE);
canvas.drawText(gifName,width/2, height /2,paint);
return;
}
long now = SystemClock.uptimeMillis();
int relTime = (int) ((now - startTime) % gifMovie.duration());
gifMovie.setTime(relTime);
gifMovie.draw(canvas, 0, 0);
this.invalidate();
}
private void initGif(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.GifAnimView, 0, 0);
gifName = a.getString(R.styleable.GifAnimView_gifSrc);
try {
gifStream =context.getAssets().open(gifName);
gifMovie = Movie.decodeStream(gifStream);
startTime = SystemClock.uptimeMillis();
} catch (IOException e) {
e.printStackTrace();
}
paint = new Paint();
paint.setTextSize(40);
paint.setTextAlign(Paint.Align.CENTER);
paint.setStyle(Paint.Style.FILL);
a.recycle();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
this.width = w;
this.height = h;
super.onSizeChanged(w, h, oldw, oldh);
}
}
create attrs.xml in res/values folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="GifAnimView">
<attr name="gifSrc" format="string" localization="suggested" />
</declare-styleable>
</resources>
copy your.gif file into src/main/assets/ folder
activity_main.xml:
you can use app:gifSrc attribute as name of your gif that exist in assets folder.
// ....
<com.app.samplegif.GifAnimView
android:id="#+id/gif_view"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
app:gifSrc="your.gif" />
// ....

How to draw lines over ImageView on Android?

I am trying to develop a simple map application, which will display a map in the screen.
When the user moves the cursor on screen, I want to display 2 perpendicular lines over my map. I had tried many examples to get an idea for that, but unfortunately, didn't succeed.
How can I make this?
And as one previous questionhere I had tried. but didn't get the answer. Can anyone guide me?
My main.xml is as following:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView android:id="#+id/main_imagemap"
android:src="#drawable/worldmap"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
And my activity file(i had just started it..)
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class LineMapActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView map_image = (ImageView)findViewById(R.id.main_imagemap);
}
}
And as in that link, i had also added MyImageView.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.widget.ImageView;
public class MyImageView extends ImageView
{
public MyImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
canvas.drawLine(0, 0, 20, 20, p);
super.onDraw(canvas);
}
}
Now how can i add this MyImageView to my app?
Finally I figured out a solution. It's a simple program which draws a line over an Image.
Here is my main.xml file (com.ImageDraw.MyImageView is my custom view, code below):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.ImageDraw.MyImageView android:id="#+id/main_imagemap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
And here is the main activity:
import android.app.Activity;
import android.os.Bundle;
public class MyActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
and this is my custom image view (MyImageView):
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MyImageView extends SurfaceView implements SurfaceHolder.Callback
{
private CanvasThread canvasthread;
public MyImageView(Context context) {
super(context);
getHolder().addCallback(this);
canvasthread = new CanvasThread(getHolder(), this);
setFocusable(true);
}
public MyImageView(Context context, AttributeSet attrs)
{
super(context,attrs);
getHolder().addCallback(this);
canvasthread = new CanvasThread(getHolder(), this);
setFocusable(true);
}
protected void onDraw(Canvas canvas) {
Log.d("ondraw", "ondraw");
Paint p = new Paint();
Bitmap mapImg = BitmapFactory.decodeResource(getResources(), R.drawable.mybitmap);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(mapImg, 0, 0, null);
p.setColor(Color.RED);
canvas.drawLine(0, 0, 100, 100, p);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
canvasthread.setRunning(true);
canvasthread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
canvasthread.setRunning(false);
while (retry)
{
try
{
canvasthread.join();
retry = false;
}
catch (InterruptedException e) {
// TODO: handle exception
}
}
}
}
And finally here is my CanvasThread:
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class CanvasThread extends Thread
{
private SurfaceHolder surfaceHolder;
private MyImageView myImageView;
private boolean run = false;
public CanvasThread(SurfaceHolder s, MyImageView m)
{
surfaceHolder = s;
myImageView = m;
}
public void setRunning(boolean r)
{
run = r;
}
public void run()
{
Canvas c;
while(run)
{
c=null;
try
{
c= surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder) {
myImageView.onDraw(c);
}
}
finally
{
if(c!=null)
{
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
You can find more details in this tutorial
Error you are getting because you are trying to casting ImageView object to MyImageView object.
Just fix the xml to include your object instead of an imageview like so (note that com.your.package.MyImageView should be the full package name of the package containing your class and then the class name)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.your.package.MyImageView android:id="#+id/main_imagemap"
android:src="#drawable/worldmap"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>

Android Custom Component not being displayed

Having a problem with Android Custom components. Trying to draw an oval shape but nothing happening.
I have this line in layout xml file
<android.project.realtimedata.DemoView android:id="#+id/demoView"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
Here is the code for my custom component class.
package android.project.realtimedata;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.util.AttributeSet;
import android.view.View;
public class DemoView extends View{
ShapeDrawable thisGauge = null;
public DemoView(Context context){
super(context);
init();
}
public DemoView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
private void init(){
int x = 10;
int y = 10;
int width = 300;
int height = 50;
thisGauge = new ShapeDrawable(new OvalShape());
thisGauge.getPaint().setColor(0xff74AC23);
thisGauge.setBounds(x, y, x + width, y + height);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
thisGauge.draw(canvas);
}
}
I also have this line in onCreate method of Activity
demoView = (DemoView) findViewById(R.id.demoView);
Whenever I launch the application the custom component is not there.
I tried looking at it from LogCat and it definitely gets created.
What am I missing here?
Thanks in advance.
Make sure that you calling findViewById(R.id.demoView) after calling setContentView(...). To ensure that your view is being inflated, you can call Log.d("DemoView", "Created") from inside your DemoView constructor.

Categories

Resources