How to set canvas size? - java

I have a class named SeatsPanel where I draw seats (using drawRect) in the onDraw method. The onDraw method uses Canvas as a parameter, but how do you set size of the Canvas? The reason why I'm asking this question is because this class is being inflated in another class. I know that the canvas has the default height and width of the phone, but I need to make it smaller. How can I do this?
Any help would be appreciated.

I've tried to implement a simple application that draws a black rect within the main activity, that is drawn pushing a button. For example, in the MainActivity:
private Button button1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1=(Button)findViewById(R.id.button);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
switch(v.getId()){
case R.id.button:
LinearLayout ll=(LinearLayout)findViewById(R.id.linearLayout1);
System.out.println(ll.getWidth()+" "+ll.getHeight());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ll.getWidth(),ll.getHeight());
YourView yourView = new YourView(getBaseContext());
yourView.setBackgroundColor(Color.WHITE);
ll.addView(yourView,params);
break;
}
}
});
}
And in the YourView class:
private Bitmap savedBitmap;
public YourView(Context context) {
super(context);
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
System.out.println(canvas.getWidth()+" "+canvas.getHeight());
Paint textPaint = new Paint();
textPaint.setARGB(255, 0, 0, 0);
textPaint.setTextAlign(Paint.Align.RIGHT);
textPaint.setTextSize(11);
textPaint.setTypeface(Typeface.DEFAULT);
canvas.drawColor(Color.WHITE);
System.out.println(canvas.getWidth());
System.out.println(canvas.getHeight());
canvas.drawRect(200, 20, 500, 100, textPaint);
}
The main.xml:
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Push the button and draw a Rect" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>

Might not be applicable in your case, but this works for me
Bitmap animation = BitmapFactory.decodeResource(mContext.getResources(), resourceId, mBitmapOptions); //Get a bitmap from a image file
// Create a bitmap for the part of the screen that needs updating.
Bitmap bitmap = Bitmap.createBitmap(animation.getWidth(), animation.getHeight(), BITMAP_CONFIG);
bitmap.setDensity(DisplayMetrics.DENSITY_DEFAULT);
Canvas canvas = new Canvas(bitmap);
This sets the canvas to the size of the bitmap

Related

Android: This imageView is not found?

I'm loading a bitmap from the input stream and putting it on an imageview. THen I have a button that should draw a circle on the bitmap. The error is that the imageview (called 'touch') is not found inside the onClickListener...how do I fix this? When I press the button nothing happens. (Note: ZoomInZoomOut class is an extension of Imageview)
try {
java.io.FileInputStream in = this.openFileInput(path);
Bitmap bitmap = BitmapFactory.decodeStream(in);
ZoomInZoomOut touch = (ZoomInZoomOut)findViewById(R.id.IMAGEID);
touch = arrangeImageView(touch);
touch.setImageBitmap(bitmap);
in.close();
Button draw = (Button) findViewById(R.id.draw);
draw.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
Bitmap imageBitmap = Bitmap.createBitmap(200,
200, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(imageBitmap);
Paint p = new Paint();
p.setAntiAlias(true);
p.setColor(Color.BLUE);
canvas.drawCircle(60, 50, 25, p);
/////////////////////Error is on the next line:
touch.setImageBitmap(imageBitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
}
Here is the XML:
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#drawable/background"
tools:context="com.commonsware.android.test1.ImageDisplayActivity"
>
<com.commonsware.android.test1.ZoomInZoomOut
android:id="#+id/IMAGEID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="o"
android:id="#+id/draw"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
The touch variable is defined in another scope. If you want more explication, check this link.
To fix your problem change your code like this:
final ZoomInZoomOut touch = (ZoomInZoomOut)findViewById(R.id.IMAGEID);
Or you can also create a variable in your class if you need to access it from another scope later:
private ZoomInZoomOut touch;
and instantiate like this:
touch = (ZoomInZoomOut)findViewById(R.id.IMAGEID);

Move imageview after animation (update position)

I am trying to to do a translate animation on an image view from the bottom to the middle of the screen. Upon finish of the animation, I want the image view to stay there. I dont want the setFillAfter(true) because I want the actual position of the imageview to be updated.
I do it currently by having 2 image view (one at the start of animation and one at the end) and I play with the setVisibility to achieve this. Is this the correct way to do things? Here is the code I used:
<ImageView
android:id="#+id/ivStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/typer_step_1"
android:gravity="center"
/>
<ImageView
android:id="#+id/ivMiddle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/typer_step_1"
android:gravity="center"
android:visibility="invisible"
/>
TranslateAnimation translate = new TranslateAnimation(0, mDestLoc1[0]-mSrcLoc1[0], 0, mDestLoc1[1]-mSrcLoc1[1]);
translate.setDuration(2000);
translate.setAnimationListener(new AnimationListener(){
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {
ivMiddle.setVisibility(View.VISIBLE)
ivStart.setVisibility(View.INVISIBLE)
}
#Override
public void onAnimationRepeat(Animation animation) {}
});
ivStart.startAnimation(translate);
Then you must set new LayoutParams for your View which is animating. When animation finishes, in your onAnimationEnd part, set new position of your View.
TranslateAnimation translate = new TranslateAnimation(0, mDestLoc1[0]-mSrcLoc1[0], 0, mDestLoc1[1]-mSrcLoc1[1]);
translate.setDuration(2000);
translate.setAnimationListener(new AnimationListener(){
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {
RelativeLayout.LayoutParams par = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
par.topMargin = mDestLoc1[1]-mSrcLoc1[1];
par.leftMargin = mDestLoc1[0]-mSrcLoc1[0];
view.setLayoutParams(par);
}
#Override
public void onAnimationRepeat(Animation animation) {}
});
view.startAnimation(translate);
Snake use my code this ll help you,
//Call this in your onCreate
private void StartAnimationsDtoU()
{
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alphadtou);
anim.reset();
RelativeLayout l=(RelativeLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.logo);
iv.setImageResource(R.drawable.earth);
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
iv.clearAnimation();
iv.startAnimation(anim);
}
This is your linear layout with an image which ll move from down to middle of the screen.
<RelativeLayout 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:id="#+id/lin_lay">
<ImageView
android:id="#+id/logo"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#drawable/earth" />
and this ll be your xml file for translation i.e translate.xml ...
<set xmlns:android="http://schemas.android.com/apk/res/android"><translate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%"
android:toXDelta="0%"
android:fromYDelta="200%"
android:toYDelta="0%"
android:duration="4000"
android:zAdjustment="top" /></set>
and this ll be your down to up alphadtou.xml...
<?xml version="1.0" encoding="utf-8"?><alpha
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="1000" />
and also override onAttachedToWindow method like this...
#Override
public void onAttachedToWindow()
{
// TODO Auto-generated method stub
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
Hope this ll help you alot.
If you want the actual starting position of the image view you can get it at the time of animationStart And you can use setFillAfter(true). The setFillAfter(true) will update the position after the animation end.
If you need the new position you can use the setFilter(true). If you are not ready to use setFillAfter(true) (if you need the older position), then you have done the right thing by having two Image Views. But its better to get the position in animationStart and use setFillAfter(true).
Add this line before starting the animation
translate.setFillAfter(true);

split up a linear layout background into different colored parts

For a ListView, I want to give the individual ListView elements some kind of progress indicator - so to speak, I need a list of progress bars.
However, each of the listview elements have some text overlay in the form of a TextView that should not be affected by the progress bar at all.
I think pictures can tell more than words in this case, so here is pretty much what I want:
I know I can add "sublayouts" to the individual LinearLayouts and change the weight programmatically, which looks somewhat like this:
<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="horizontal">
<LinearLayout
android:id="#leftSide"
android:background="#color/green"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.8" >
</LinearLayout>
<LinearLayout
android:id="#rightSide"
android:background="#color/red"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.2" >
</LinearLayout>
</LinearLayout>
and then programmatically change the weight for both sides (completed and uncompleted):
float weightLeft = 0.8f;
float weightRight = 1f-weightLeft;
android.widget.LinearLayout.LayoutParams paramsLeft = new android.widget.LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, weightLeft);
LinearLayout left = (LinearLayout) findViewById(R.id.leftside);
left.setLayoutParams(paramsLeft);
android.widget.LinearLayout.LayoutParams paramsRight = new android.widget.LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, weightRight);
LinearLayout right = (LinearLayout) findViewById(R.id.rightside);
left.setLayoutParams(paramsRight);
But - the question now is, how do I make the textviews sit on the parent linear layout and ignore the children LinearLayouts ?
I can also imagine there is a way to just split up the distribution of the background parts using drawables, but I have no clue how to do that, especially not programmatically.
Any help is appreciated!
try this custom Drawable, mFraction is [0..1]:
public class FractionDrawable extends Drawable {
private Paint mPaint;
private float mFraction;
public FractionDrawable(float fraction) {
mPaint = new Paint();
setFraction(fraction);
}
public void setFraction(float fraction) {
mFraction = fraction;
invalidateSelf();
}
#Override
public void draw(Canvas canvas) {
Rect b = getBounds();
mPaint.setColor(0xff00aa00);
float x = b.width() * mFraction;
canvas.drawRect(0, 0, x, b.height(), mPaint);
mPaint.setColor(0xffaa0000);
canvas.drawRect(x, 0, b.width(), b.height(), mPaint);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}

Android App - Drawing Bitmap from Activity

I am trying to draw a simple .png file to the screen. I am using the following code:
public class EditMindMapActivity extends Activity {
private Button HomeButton;
private Button SaveButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_mind_map);
//creating dummy array:
List<String> mindMapArrayListLabels = new ArrayList<String>();
int mindMapArrayListImgs[] = new int[100]; //length 100 is arbitrary
mindMapArrayListLabels.add("Schedule");
mindMapArrayListImgs[0] = R.drawable.pyr01;
mindMapArrayListLabels.add("Stuff01");
mindMapArrayListImgs[1] = R.drawable.tube01;
mindMapArrayListLabels.add("Stuff02");
mindMapArrayListImgs[2] = R.drawable.cone01;
//draw the first image to screen
View view01 = new View(this);
//find relative layout, attach view to it.
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.RelativeLayout01);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
relativeLayout.addView(view01,lp);
Canvas canvas01 = new Canvas();
canvas01.drawBitmap(BitmapFactory.decodeResource(getResources(), mindMapArrayListImgs[0]), 10, 10, null);
view01.draw(canvas01);
}
}
The above doesn't do anything - the screen appears blank. I want to display the image R.drawable.pyr01 on screen.
Create a custom view and draw the image. Add the custom view to your relative layout as a child. Modify the below according to your needs.
activity_main.xml
<RelativeLayout 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"
android:id="#+id/rl"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Button" />
</RelativeLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rl);
MyView mv = new MyView(this);
relativeLayout.addView(mv);
}
class MyView extends View
{
public MyView(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.afor), 100 ,100, null);
}
}
Resulting snap shot

Android AnimationDrawable stopping upon return to home screen

I am developing a game in Android in which the launcher screen has 2 AnimationDrawables on it.
The animations run fine together, however when I navigate away from the screen and then hit back to return to it, one of the animations stops, and the other continues.
My code is below:
static AnimationDrawable animation;
static AnimationDrawable animation2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.j0), 200);
animation.addFrame(getResources().getDrawable(R.drawable.j1), 200);
animation.addFrame(getResources().getDrawable(R.drawable.j2), 200);
animation.addFrame(getResources().getDrawable(R.drawable.j3), 200);
animation.setOneShot(false);
animation2 = new AnimationDrawable();
animation2.addFrame(getResources().getDrawable(R.drawable.logo), 250);
animation2.addFrame(getResources().getDrawable(R.drawable.logo1), 250);
animation2.setOneShot(false);
ImageView imageAnim = (ImageView) findViewById(R.id.imageView1);
imageAnim.setBackgroundDrawable(animation);
imageAnim.post(new MenuAnimate());
ImageView imageAnima = (ImageView) findViewById(R.id.imageView2);
imageAnima.setBackgroundDrawable(animation2);
imageAnima.post(new MenuAnimate2());
class MenuAnimate implements Runnable {
public void run() {
Menu.animation.start();
}
}
class MenuAnimate2 implements Runnable {
public void run() {
Menu.animation2.start();
}
}
Xml 'menu':
<LinearLayout android:orientation="horizontal" android:layout_height="fill_parent" android:layout_width="wrap_content" android:weightSum="1" android:layout_weight="0.93">
<ImageView android:id="#+id/imageView1" android:layout_height="match_parent" android:layout_width="wrap_content"></ImageView>
<ImageView android:id="#+id/imageView2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="bottom"></ImageView>
</LinearLayout>
If anyone has any idea it would be amazing.

Categories