'set the canvas size - Android
I want to keep the same size of the bitmap for the canvas, because when I add the custom view to the LinearLayout shows the canvas with different size and I want to set the size of the canvas like bitmap object.
Part of the code:
public class TESTActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l = new LinearLayout(this);
l.setOrientation(1);
Button b1 = new Button(this);
Button b2 = new Button(this);
View mV = new MyView(this);
l.addView(b1);
l.addView(b2);
l.addView(mV);
setContentView(l);
}
public class MyView extends View {
public MyView(Context c) {
super(c);
mBitmap = Bitmap.createBitmap(480, 300, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
...
}
...
}
}
Solution 1:[1]
The Canvas class holds the "draw" calls. Canvas(Bitmap bitmap)
Construct a canvas with the specified bitmap to draw into. canvas will take the size of the the draw object. so by setting size of bitmap you can set size of canvas.
Solution 2:[2]
If you want to draw on canvas with your custom height and width you have to call setContentView(android.view.View yourView , android.view.Viewgroup.LayoutParam yourLayout) in your activity class.Because by default setContentView(View view) method use full width and height.So you have to use its overloaded method with two parameter along with your desired. See documentation for more info.And don`t use only LayoutParams() constructor to create its object. Use it by writing its full path like android.view.ViewGroup.LayoutParams. Because there are some other classes with same name in Android SDK.If you only use LayoutParams Eclipse may not find correct class so use full path.
MyView customView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
customView = new MyView(getApplicationContext());
android.view.ViewGroup.LayoutParams lp = new android.view.ViewGroup.LayoutParams(100,200);//100 is width and 200 is height
setContentView(customView, lp);
customView.setOnClickListener(this);
}`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sunil Kumar Sahoo |
Solution 2 | AsifBuet047 |