i googled coverflow code i found one useful and work great to me (im not professional in android development ), what i need it.
when click on each image it will stream predetermined mp3 song for each image and another click will stop it ,
so each image will have different mp3 song which all mp3 songs stored in app it self .
public class CoverFlowExample 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.aa,
R.drawable.aab,
R.drawable.aabb,
R.drawable.aabbb,
R.drawable.aac,
};
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(430, 430));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
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)));
}
}
}
Related
I am trying to build a simple game on android and while setting the background image and other image assets on my main screen it is appearing too big as shown in the below image.
The actual size of the image is 1920x1080 and I want it to fit my screen like the image shown below:
The code for I have used is:
public class PoliceView extends View {
private Bitmap police;
private Bitmap background;
private Paint scorePaint = new Paint();
private Bitmap life[] = new Bitmap[2];
public PoliceView(Context context) {
super(context);
police = BitmapFactory.decodeResource(getResources(),R.drawable.police);
background = BitmapFactory.decodeResource(getResources(),R.drawable.gamebackground);
scorePaint.setColor(Color.BLACK);
scorePaint.setTextSize(70);
scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
scorePaint.setAntiAlias(true);
life[0] = BitmapFactory.decodeResource(getResources(),R.drawable.heart);
life[1] = BitmapFactory.decodeResource(getResources(),R.drawable.brokenheart);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//The order of draw matters as objects are drawn in this same order
canvas.drawBitmap(background,0,0,null);
canvas.drawBitmap(police, 0, 0, null);
canvas.drawText("Score:",20, 60, scorePaint);
//Three lives for the police
canvas.drawBitmap(life[0],580, 10, null);
canvas.drawBitmap(life[0],680, 10, null);
canvas.drawBitmap(life[0],780, 10, null);
}}
How can I resize the images to fit the screen??
i use this code for resize image
Bitmap tmp = BitmapFactory.decodeFile(mPath);
ResizeWidth = (int) (your size);
ResizeHeight = (int) (your size);
Bitmap bitmap = Bitmap.createBitmap(ResizeWidth, ResizeHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Bitmap scaled = Bitmap.createScaledBitmap(tmp, ResizeWidth, ResizeHeight, true);
int leftOffset = 0;
int topOffset = 0;
canvas.drawBitmap(scaled, leftOffset, topOffset, null);
How to resize bitmap in canvas?
canvas.save(); // Save current canvas params (not only scale)
canvas.scale(scaleX, scaleY);
canvas.restore(); // Restore current canvas params
scale = 1.0f will draw the same visible size bitmap
I'm setting up an eye detection android project and I want to draw probabilities using Canvas, I'm using Firebase ML kit for custom models
I have successfully drawn only one point.
I would like to draw points ( probabilities from tflite model that I have ).
I tried using those functions :
private void useInferenceResult(float[] probabilities) throws IOException {
// [START mlkit_use_inference_result]
String[] result=new String[80];
float x=0;
float y=0;
ArrayList<Point> listpoint= new ArrayList<Point>();
for (int i = 0; i < probabilities.length; i++) {
Log.i("MLKit", String.format("%1.4f", probabilities[i]));
x=probabilities[i];
y=probabilities[i+1];
Point p=new Point(x,y);
i=i+1;
p.setX(x);
p.setY(y);
Log.i("Information1 ","valeur 1 "+p.getX());
listpoint.add(p);
Log.i("Information2 ","valeur 2 "+p.getX());
}
for(int j=0;j<listpoint.size();j++){
Log.e("Information","work");
Log.e("Resultat","point_"+j+"("+listpoint.get(j).getX()+", "+listpoint.get(j).getY()+")");
float xx=listpoint.get(j).getX()*100;
float yy=listpoint.get(j).getY()*100;
drawpoint(image2,0.20958422f * 100,0.6274962f * 100,1);
drawpoint(image2, 0.20460524f * 100,0.6708223f * 100,1);
}
}
//drawpoint function
private void drawpoint(ImageView imageView,float x,float y, int raduis){
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.imgg,myOptions);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(x,y, raduis, paint);
imageView = (ImageView)findViewById(R.id.imageView);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap);
}
but I didn't get any result just one point drawn.
How can I draw multiples points on imageView?
I solved my problem by changing some lines of code, I declare those variables on the top and I create objects after setContentView:
BitmapFactory.Options myOptions;
Canvas canvas;
Bitmap mutableBitmap;
Bitmap workingBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_open= findViewById(R.id.btn_open);
image2= findViewById(R.id.imageView);
myOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.image000880,myOptions);
paint= new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
workingBitmap = Bitmap.createBitmap(bitmap);
mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
canvas = new Canvas(mutableBitmap);
private void drawpoint(ImageView imageView,float x,float y, int raduis){
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
// ArrayList<Point> list= new ArrayList<>();
canvas.drawCircle(x,y, raduis, paint);
imageView = (ImageView)findViewById(R.id.imageView);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap);
}
Hope this solution will help others who have the same situation
Simple ImageView Descendent class.
public class CiclesImageView extends AppCompatImageView {
private ArrayList<PointF> theDots = new ArrayList<>();
private Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
public CirclesImageView(Context context) {
super(context);
setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN)
drawDot(new PointF(event.getX(),event.getY()));
return performClick();
}
});
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
for (PointF pt:theDots)canvas.drawCircle(pt.x,pt.y,5,paint);
}
public void drawDot(PointF dotPoint){
theDots.add(dotPoint);
invalidate();
}
}
This imageView is used the same way you use any other imageView, except if you touch it, it will draw a circle on itself. If you want to draw your own circles, the drawDot(pointF) is public.
I'm currently trying to put in a color from my colors resources xml into my app using ContextCompact.getColor() but for some reason I cannot pass in a single version of context.
I'm using a class as a handler so I am not trying to pass in from an activity. In my activity I can use them, but in my class I cannot pass in getActivityContext() this etc. Nothing works. What do I do?
Also, I'm adding the color to a canvas so I cannot add the color in in an xml.
canvas.drawColor(Color.BLACK);
Is what I'm currently forced to use. I want to replace it with a color from my xml. ( I'm trying to set the background of the canvas essentially )
full code of my class: (I'm making this app as a "note" app so that I can look back on it for future projects, hence all the comments)
public class GameHandling {
private SurfaceHolder holder;
private Resources resources;
private int screenWidth;
private int screenHeight;
private Ball ball;
private Bat player;
private Bat opponent;
public GameHandling(int width, int height, SurfaceHolder holder, Resources resources){
this.holder = holder;
this.resources = resources;
this.screenWidth = width;
this.screenHeight = height;
this.ball = new Ball(screenWidth, screenHeight, 400, 400);
this.player = new Bat(screenWidth, screenHeight, 0, 0, Bat.Position.LEFT);
this.opponent = new Bat(screenWidth, screenHeight, 0, 0, Bat.Position.RIGHT);
}
// setting the ball images to be drawn
public void inIt(){
Bitmap ballShadow = BitmapFactory.decodeResource(resources, R.mipmap.grey_dot);
Bitmap ballImage = BitmapFactory.decodeResource(resources, R.mipmap.red_dot);
Bitmap batPlayer = BitmapFactory.decodeResource(resources, R.mipmap.bat_player);
Bitmap batOpponent = BitmapFactory.decodeResource(resources, R.mipmap.bat_opponent);
ball.inIt(ballImage, ballShadow, 2, 0);
player.inIt(batPlayer, batPlayer, 0, 0);
opponent.inIt(batOpponent, batOpponent, 0, 0);
}
// calling Balls update method to update the ball
public void update(long elapsed){
ball.update(elapsed);
}
public void draw(){
Canvas canvas = holder.lockCanvas(); // Making a canvas object to draw on - .lockcanvas locks canvas
if(canvas != null) {
// draw in area between locking and unlocking
canvas.drawColor(Color.BLACK);
ball.draw(canvas);
player.draw(canvas);
opponent.draw(canvas);
holder.unlockCanvasAndPost(canvas); //-unlockcanvasandposts unlocks the canvas
}
}
}
Change your constructor to this and use ContextCompat.getColor(context,... pattern.
Wherever you are creating this class (activity/fragment), pass the context calling either getActivity() or getApplicationContext()
new GameHandling( getActivity()/getApplicationContext(), ...)
public GameHandling(Context context, int width, int height, SurfaceHolder holder, Resources resources){
this.context = context;
this.holder = holder;
this.resources = resources;
this.screenWidth = width;
this.screenHeight = height;
this.ball = new Ball(screenWidth, screenHeight, 400, 400);
this.player = new Bat(screenWidth, screenHeight, 0, 0, Bat.Position.LEFT);
this.opponent = new Bat(screenWidth, screenHeight, 0, 0, Bat.Position.RIGHT);
}
I kind of came up with a workaround, I created an image with my desirable color and then used that as the background of the app.
However it is still a workaround, so it doesn't solve my issue
I am creating an app and want my ui to scale with the phone. I am importing bitmaps into a canvas and drawing them as follows:
public class MainMenu extends View {
private RectF titleBounds, playBounds, scoreBounds, soundBounds, creditBounds;
private Paint titlePaint, playPaint;
private boolean playClick = false, startPlay = false, scoreClick = false, startScore = false, soundClick = false, startSound = false, creditsClick = false, startCredits = false;
public Bitmap play;
public Bitmap playGlow;
public Bitmap sound;
public Bitmap soundGlow;
public int screenWidth, screenHeight;
public MainMenu(Context context) {
super(context);
titleBounds = new RectF();
playBounds = new RectF();
scoreBounds = new RectF();
soundBounds = new RectF();
creditBounds = new RectF();
titlePaint = new Paint();
playPaint = new Paint();
play = BitmapFactory.decodeResource(getResources(), R.drawable.play);
playGlow = BitmapFactory.decodeResource(getResources(), R.drawable.playglow);
sound = BitmapFactory.decodeResource(getResources(), R.drawable.sound);
soundGlow = BitmapFactory.decodeResource(getResources(), R.drawable.soundglow);
// Get window size and save it to screenWidth and screenHeight.
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
}
#Override protected void onDraw(Canvas canvas) {
ViewGroup parent = (ViewGroup)getParent();
playBounds.set(screenWidth / 2 - play.getWidth() / 2, screenHeight * 1/3 - play.getHeight() / 2, playBounds.left + play.getWidth(), playBounds.top + play.getHeight());
soundBounds.set(scoreBounds.centerX() - sound.getWidth() / 2, scoreBounds.bottom + 10, soundBounds.left + sound.getWidth(), soundBounds.top + sound.getHeight());
The problem is theres nothing to scale the image to fit the phone, it just reads the x and y size of the image I import. What method is there for scaling images?
Use the createScaledBitmap of the Bitmap class
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
It will scale your bitmap but not greater than the width and height that is because it can cause blurriness to your bitmap.
documentation:
Creates a new bitmap, scaled from an existing bitmap, when possible.
If the specified width and height are the same as the current width and height of the source bitmap,
the source bitmap is returned and no new bitmap is created.
for full screen
bitmap = Bitmap.createScaledBitmap(bitmap, screenWidth , screenHeight , true);
So far, my image starts at 0,0 and scales properly. There is a black bar under it. How can I align it so that it is centered along the y, with a black bar above and below the image?
edit: also, what are "this.getWidth(), this.getHeight()" referring to when I make the object "dest" - the width of mBitmap? The documentation does say they represent the width of the view, I just want to make sure I'm correct in thinking that is it mBitmap.
public class SpotGameActivity extends Activity {
private Bitmap mBitmap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dpi2b);
setContentView(new BitMapView(this, mBitmap));
}
class BitMapView extends View {
Bitmap mBitmap = null;
public BitMapView(Context context, Bitmap bm) {
super(context);
mBitmap = bm;
}
#Override
protected void onDraw(Canvas canvas) {
//DisplayMetrics metrics = new DisplayMetrics();
//getWindowManager().getDefaultDisplay().getMetrics(metrics);
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getWidth() / aspectRatio));
String AR = Double.toString(aspectRatio);
canvas.drawBitmap(mBitmap, null, dest, paint);
Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();
}
I've now gotten the difference between the view size and image size. I've divided the difference by 2 but now, my image is align to the bottom of the screen rather than the middle of the y-axis. any tips?:
#Override
protected void onDraw(Canvas canvas) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int scrHeight = this.getHeight();
String sH = Integer.toString(scrHeight);
Log.v(TAG, "scrHeight =" + sH );
int imgHeight= mBitmap.getHeight();
String iH = Integer.toString(imgHeight);
Log.v(TAG, "imgHeight =" + iH );
int diff = scrHeight - imgHeight;
String dif = Integer.toString(diff);
Log.v(TAG, "diff =" + dif );
int dvd= diff/2;
// called when view is drawn
Paint paint = new Paint();
paint.setFilterBitmap(true);
// The image will be scaled so it will fill the width, and the
// height will preserve the image’s aspect ration
float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
Rect dest = new Rect(0, dvd, this.getWidth(),(int) (this.getWidth() / aspectRatio)+dvd);
String AR = Double.toString(dvd);
canvas.drawBitmap(mBitmap, null, dest, paint);
Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();