Add ImageView dynamically to View - android

I am making an Android game which uses the View class and I am not using an XML-layout.
All my images are drawn with canvas. Now my problem is the I cannot use a bitmap.
I am trying to add an ImageView dynamically to my View class, to use the touchable event.
Why dynamically? Because I could not use XML-layout.
Here is my code:
package com.example.poolmaster;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private int cuePosx, cuePosy;
int cueHeight, cueWeight;
double rotatingAngle;
int height;
int wwidth;
int cueHeight2, cueWeight2;
Bitmap table, stick, raise;
ImageView button = new ImageView(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rotatingAngle = 0;
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
wwidth = displaymetrics.widthPixels;
cueHeight2 = height / 2;
cueWeight2 = wwidth / 2;
System.out.println("**************************************");
System.out.println("height " + height);
System.out.println("weight" + wwidth);
System.out.println("**************************************");
// Set generic layout parameters
GamePlay custom = new GamePlay(this);
setContentView(custom);
// setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_MOVE){
// cuePosy += 10;
// System.out.println("xCORDİNATES!!!! " +ev.getX());
// System.out.println("yCORDİNATES!!!! " +ev.getY());
rotatingAngle=getAngle(ev.getX(), ev.getY());
System.out.println("Angle " +rotatingAngle);
}
if (ev.getAction()==MotionEvent.ACTION_DOWN){
System.out.println("****************** ACTİON DOWN ****************");
// cueHeight2 += 10;
// cueWeight2 += 20;
// cuePosy = 320;
}
if (ev.getAction()==MotionEvent.ACTION_UP){
System.out.println("****************** ACTİON DOWN ****************");
// cueHeight2 -= 10;
// cueWeight2 -= 20;
// cuePosy = 320;
}
return true;
}
private double getAngle(double xTouch, double yTouch) {
double theta;
theta = Math.toDegrees(Math.atan2(height / 2 - yTouch, xTouch - wwidth / 2));
return theta;
}
public class GamePlay extends View {
public GamePlay(Context context) {
super(context);
// TODO Auto-generated constructor stub
table = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
table = Bitmap.createScaledBitmap(table, wwidth, height, true);
stick = BitmapFactory.decodeResource(getResources(), R.drawable.stick);
raise = BitmapFactory.decodeResource(getResources(), R.drawable.raise);
cueHeight = stick.getHeight();
System.out.println("ıstaka " + cueHeight);
cueWeight = stick.getWidth();
cuePosx = wwidth / 2;
cuePosy = height - cueHeight - 180;
}
#SuppressLint({ "DrawAllocation", "DrawAllocation" })
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Matrix matrix = new Matrix();
matrix.setTranslate(cueWeight2, cueHeight2);
matrix.postRotate((float)rotatingAngle, cueWeight2, cueHeight2); // anti-clockwise by 90 degrees
// create a new bitmap from the original using the matrix to transform the result
Bitmap rotatedBitmap = Bitmap.createBitmap(stick, 0, 0, stick.getWidth(), stick.getHeight(), matrix, false);
canvas.save(); // Save the position of the canvas.
canvas.restore();
// Rotate the canvas.
canvas.drawBitmap(table, 0, 0, null); // Draw the ball on the rotated canvas.
canvas.drawBitmap(stick, matrix, null);
canvas.drawBitmap(raise, 0, 0, null);
invalidate();
}
}
}

This is for adding imageview to a layout where Activity class is extended
LinearLayout lL = findViewById(R.id.xmlfile_layout_id);
ImageView imgView = new ImageView(context);
imgView.setVisibility(View.VISIBLE);
lL.addView(imgView);
This is for adding imageview to a canvas where View class is extended
Initially, you cannot place any imageview, edit text or buttons using canvas. Instead, you have to draw it. So create a custom layout and draw that layout with canvas
Try this, It might help you. in onDraw(..)
LinearLayout lL = new LinearLayout(context);
ImageView imgView = new ImageView(context);
imgView.setVisibility(View.VISIBLE);
lL.addView(imgView);
lL.measure(canvas.getWidth(), canvas.getHeight());
lL.layout(0, 0, canvas.getWidth(), canvas.getHeight());
// placing the edit text at specific co-ordinates:
//canvas.translate(0, 0);
layout.draw(canvas);
And take a look at this another example : Click here
It gives another way of adding views

Use below code for that.
For Create ImageView Dynamically
ImageView mImgView1 = new ImageView(this);
For Add into your View write below code before setContentView(custom); (If GamePlay is your View Class)
custom.add(mImgView1);

Related

Android: How to detect if a point in the line drawn by canvas?

The line is drawn with a color which is different from the background color. Then put the bitmap in canvas in an array. If the color of the given point in the array is the same as line's color, then the point is in the line. In addition, I do not want to display the canvas in my app.
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btnCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCheck = (Button) findViewById(R.id.btn_check);
btnCheck.setOnClickListener(click);
}
private View.OnClickListener click = new View.OnClickListener() {
#Override
public void onClick(View v) {
int width = 60, height =60;
int startX = 15, startY = 8;
int stopX = 15, stopY = 20;
Paint paint = new Paint();
paint.setStrokeWidth(5);
paint.setColor(Color.RED);
Bitmap baseBitmap;
Canvas canvas;
baseBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(baseBitmap);
canvas.drawColor(Color.WHITE);
canvas.drawLine(startX, startY, stopX, stopY, paint);
int[] arrImage = new int[width*height];
baseBitmap.setPixels(arrImage, 0, width, 0, 0, width, height);
int[][] points = new int[][]{
{15, 8},{15, 10},
{30, 30},{40, 40}};
String result = "";
for (int i=0; i<points.length; ++i) {
int index = getPixelIndex(width, points[i][0], points[i][1]);
result = result + ":" + (arrImage[index] == Color.RED);
}
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
}
};
public int getPixelIndex(int imageWidth, int pos_x, int pos_y) {
return pos_y * imageWidth + pos_x;
}
}
But the four results are all false which is not the results I expected.
What are the errors for my code?
Your problem is this line:
baseBitmap.setPixels(arrImage, 0, width, 0, 0, width, height);
The setPixels() method replaces the pixel data in the Bitmap with the passed array, which, in this case, is all zeroes. It does not change the array's values, so they will still be all zeroes when you do your comparisons.
You want the getPixels() method instead.

Android - Draw a rect using canvas which should raise from bottom

I want to draw a stack which should raise from the bottom. For example the stack height is 400, from the height 10 it should grow till it reaches 400.
I want to do this using paint and canvas.
I don't want to do it with image view/bitmap and scale animation.
Is it possible to do this with canvas and paint? if so how to achieve it?
Thanks in advance.
You could try using something like this (have not tested myself):
Paint paint = new Paint();
paint.setColor(Color.BLACK);
for(int i = 10; i < 400; i = i + 10)
{
try
{
// To slow the for loop down, can change 100 accordingly or remove altogther
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
canvas.drawRect(0, i, 10, 0, paint); // this will make 10 x 10 square starting from bottom
invalidate();
}
What ever you do with canvas, even if you try for loop or invalidate, sleep, after all its drawing the shape in single stretch. I found the result in following way. May be it would be helpful for someone else, so adding the code here.
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
public class AndroidDraw extends Activity {
private DrawView drawView;
private int height = 300;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_draw);
CountDownTimer timer = new CountDownTimer(2000, 50) {
#Override
public void onTick(long millisUntilFinished) {
height = height - 10;
drawView = new DrawView(AndroidDraw.this, height);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
#Override
public void onFinish() {
}
};
timer.start();
}
}
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
Paint paint = new Paint();
private int height;
public DrawView(Context context, int height) {
super(context);
this.height = height;
}
#Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.RED);
canvas.drawRect(30, height, 60, 300, paint );
}
}

How to create an activity without 'setContentView(R.layout.main)'

I know its possible to create activities by doing something like the code bellow, where the view is not set from xml file but like this: setContentView(new myView(this));
What i don't understand is how to use this code but still have the ability to customize it, for instance if i wanted to add a button to the code bellow, how would i do it, because i cant simply add one to an xml layout can i?
ANY GOOD ANSWERS TO THIS WILL VERY MUCH APPRECIATED
thanks in advance!
package com.faceapp;
import android.app.Activity;
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.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;
public class FaceappActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setContentView(new myView(this));
}
private class myView extends View{
private int imageWidth, imageHeight;
private int numberOfFace = 5;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
int numberOfFaceDetected;
Bitmap myBitmap;
public myView(Context context) {
super(context);
// TODO Auto-generated constructor stub
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.face5,
BitmapFactoryOptionsbfo);
imageWidth = myBitmap.getWidth();
imageHeight = myBitmap.getHeight();
myFace = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(myBitmap, 0, 0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
for(int i=0; i < numberOfFaceDetected; i++)
{
Face face = myFace[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
canvas.drawRect(
(int)(myMidPoint.x - myEyesDistance),
(int)(myMidPoint.y - myEyesDistance),
(int)(myMidPoint.x + myEyesDistance),
(int)(myMidPoint.y + myEyesDistance),
myPaint);
}
}
}
}
^^^^^^^^^^^^^^^
Answered
How to position the button and imageview? (Ideally using relative layout)
The picture bellow shows you what i mean:
(Ignore that the image is re-sized)
NEW CODE:
package com.test;
import android.app.Activity;
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.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class TesttActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
Button button = new Button(this);
button.setText("Button!");
layout.addView(button);
myView custom = new myView(this);
layout.addView(custom);
setContentView(layout);
}
private class myView extends View{
private int imageWidth, imageHeight;
private int numberOfFace = 5;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
int numberOfFaceDetected;
Bitmap myBitmap;
public myView(Context context) {
super(context);
// TODO Auto-generated constructor stub
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.face5,
BitmapFactoryOptionsbfo);
imageWidth = myBitmap.getWidth();
imageHeight = myBitmap.getHeight();
myFace = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(myBitmap, 0, 0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
for(int i=0; i < numberOfFaceDetected; i++)
{
Face face = myFace[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
canvas.drawRect(
(int)(myMidPoint.x - myEyesDistance),
(int)(myMidPoint.y - myEyesDistance),
(int)(myMidPoint.x + myEyesDistance),
(int)(myMidPoint.y + myEyesDistance),
myPaint);
}
}
}
}
You can pass setContentView() any form of view, to be the root view of your layout. Below is a dynamically built LinearLayout with a Button and your myView.
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
// Define the LinearLayout's characteristics
layout.setGravity(Gravity.CENTER);
layout.setOrientation(LinearLayout.VERTICAL);
// Set generic layout parameters
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
button.setText("Button!");
layout.addView(button, params); // Modify this
myView custom = new myView(this);
layout.addView(custom, params); // Of course, this too
setContentView(layout);
}
}
Understand that you can only add child views to your root view if you pass setContentView() a ViewGroup; like RelativeLayout, LinearLayout, etc. In other words you cannot do this:
myView custom = new myView(this);
Button button = new Button(this);
button.setText("Button!");
custom.addView(button);
// Nope! Method "addView()" does not exist for a regular View...
setContentView(custom);
Also, naming convention suggests that each word in a class name should have the first letter capitalized. So myView ought to be MyView, at a minimum it makes your code easier to read for other programmers and the compiler will highlight your class variables with the correct color.

Coverflow animation for listview in gallery

I am implementing a gallery containing series of vertical scrolling listviews. I have googled for similar implementation and i got coverflow widget specified here : http://www.inter-fuser.com/2010/01/android-coverflow-widget.html But it only deals with images converted as bitmaps for scaling and rotating in customized gallery view. As my implementation needs vertically scrolling listviews, i need some help.
Can i reuse this code replacing images with my listviews? or is there any customized gallery which suits my requirement. Any help would be appreciated.
Attached safari bookmark page for reference. I want view like this where i should be able to scroll each column as vertically scrollable listviews and horizontally scrollable gallery.
Have a Look at my answer
There are three classes should be added in your activity packge
1 CoverAbsSpinner.java
2 CoverAdapterView.java
3 CoverFlow
Call thease classes from your activity . The way to call CoverFlow from activity
import java.io.FileInputStream;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class CoverFlowActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CoverFlow coverFlow;
coverFlow = new CoverFlow(this);
coverFlow.setAdapter(new ImageAdapter(this));
ImageAdapter coverImageAdapter = new ImageAdapter(this);
coverImageAdapter.createReflectedImages();
coverFlow.setAdapter(coverImageAdapter);
coverFlow.setSpacing(-15);
coverFlow.setSelection(8, true);
setContentView(coverFlow);
//Use this if you want to use XML layout file
//setContentView(R.layout.main);
//coverFlow = (CoverFlow) findViewById(R.id.coverflow);
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private FileInputStream fis;
private Integer[] mImageIds = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d
};
private ImageView[] mImages;
public ImageAdapter(Context c) {
mContext = c;
mImages = new ImageView[mImageIds.length];
}
public boolean createReflectedImages() {
//The gap we want between the reflection and the original image
final int reflectionGap = 4;
int index = 0;
for (int imageId : mImageIds) {
Bitmap originalImage = BitmapFactory.decodeResource(getResources(),
imageId);
int width = originalImage.getWidth();
int height = originalImage.getHeight();
//This will not scale but will flip on the Y axis
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
//Create a Bitmap with the flip matrix applied to it.
//We only want the bottom half of the image
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);
//Create a new bitmap with same width but taller to fit reflection
Bitmap bitmapWithReflection = Bitmap.createBitmap(width
, (height + height/2), Config.ARGB_8888);
//Create a new Canvas with the bitmap that's big enough for
//the image plus gap plus reflection
Canvas canvas = new Canvas(bitmapWithReflection);
//Draw in the original image
canvas.drawBitmap(originalImage, 0, 0, null);
//Draw in the gap
Paint deafaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
//Draw in the reflection
canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);
//Create a shader that is a linear gradient that covers the reflection
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
TileMode.CLAMP);
//Set the paint to use this shader (linear gradient)
paint.setShader(shader);
//Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
//Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width,
bitmapWithReflection.getHeight() + reflectionGap, paint);
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmapWithReflection);
imageView.setLayoutParams(new CoverFlow.LayoutParams(120, 180));
imageView.setScaleType(ScaleType.MATRIX);
mImages[index++] = imageView;
}
return true;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
//Use this code if you want to load from resources
//ImageView i = new ImageView(mContext);
//i.setImageResource(mImageIds[position]);
//i.setLayoutParams(new CoverFlow.LayoutParams(130, 130));
//i.setScaleType(ImageView.ScaleType.MATRIX);
//return i;
return mImages[position];
}
/** Returns the size (0.0f to 1.0f) of the views
* depending on the 'offset' to the center. */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
}
The output just like

Coverview widget in .xml (android)

Coverview is a widget ive implemented from http://www.inter-fuser.com/2010/02/android-coverflow-widget-v2.html and it works until i want to use it .xml instead to add buttons and stuff. I have no idea how to link the two and any help would be really appreciated
My main activity:
package cover.flow.test;
import java.io.FileInputStream;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class CoverFlowExampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CoverFlow coverFlow;
coverFlow = new CoverFlow(this);
coverFlow.setAdapter(new ImageAdapter(this));
ImageAdapter coverImageAdapter = new ImageAdapter(this);
//coverImageAdapter.createReflectedImages();
coverFlow.setAdapter(coverImageAdapter);
coverFlow.setSpacing(-25);
coverFlow.setSelection(4, true);
coverFlow.setAnimationDuration(1000);
setContentView(coverFlow);
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private FileInputStream fis;
private Integer[] mImageIds = {
R.drawable.kasabian_kasabian,
R.drawable.starssailor_silence_is_easy,
R.drawable.killers_day_and_age,
R.drawable.garbage_bleed_like_me,
R.drawable.death_cub_for_cutie_the_photo_album,
R.drawable.kasabian_kasabian,
R.drawable.massive_attack_collected,
R.drawable.muse_the_resistance,
R.drawable.starssailor_silence_is_easy
};
private ImageView[] mImages;
public ImageAdapter(Context c) {
mContext = c;
mImages = new ImageView[mImageIds.length];
}
public boolean createReflectedImages() {
//The gap we want between the reflection and the original image
final int reflectionGap = 4;
int index = 0;
for (int imageId : mImageIds) {
Bitmap originalImage = BitmapFactory.decodeResource(getResources(),
imageId);
int width = originalImage.getWidth();
int height = originalImage.getHeight();
//This will not scale but will flip on the Y axis
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
//Create a Bitmap with the flip matrix applied to it.
//We only want the bottom half of the image
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);
//Create a new bitmap with same width but taller to fit reflection
Bitmap bitmapWithReflection = Bitmap.createBitmap(width
, (height + height/2), Config.ARGB_8888);
//Create a new Canvas with the bitmap that's big enough for
//the image plus gap plus reflection
Canvas canvas = new Canvas(bitmapWithReflection);
//Draw in the original image
canvas.drawBitmap(originalImage, 0, 0, null);
//Draw in the gap
Paint deafaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
//Draw in the reflection
canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);
//Create a shader that is a linear gradient that covers the reflection
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
TileMode.CLAMP);
//Set the paint to use this shader (linear gradient)
paint.setShader(shader);
//Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
//Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width,
bitmapWithReflection.getHeight() + reflectionGap, paint);
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmapWithReflection);
imageView.setLayoutParams(new CoverFlow.LayoutParams(120, 180));
imageView.setScaleType(ScaleType.MATRIX);
mImages[index++] = imageView;
}
return true;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
//Use this code if you want to load from resources
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new CoverFlow.LayoutParams(130, 130));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
//Make sure we set anti-aliasing otherwise we get jaggies
BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
drawable.setAntiAlias(true);
return i;
//return mImages[position];
}
/** Returns the size (0.0f to 1.0f) of the views
* depending on the 'offset' to the center. */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
}
My main.xml (this is what ive tries to link but with no luck)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<cover.flow.test.CoverFlow
android:id="#+id/coverflow"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_alignParentTop="true" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
To link with the view you need something like
setContentView(R.layout.main);
and remove the code creating the CoverFlow instance (instead get it with findViewById, etc.)

Categories

Resources