Android Canvas Drawline Not Drawing On Mainactivity
I want to draw a line on the Main Activity using Canvas. The problem is, it is not drawing anything. I have the following code: Bitmap bitmap = Bitmap.createBitmap(1920, 1080, Bit
Solution 1:
you can display the bitmap like that:
canvas.drawBitmap(bmp, positionX, positionY, paint);
in your case you can try somthing like this:
canvas.drawBitmap(bitmap, 0, 0, null);
but you need to use a diffrent canvas for it. The canvas wich let you draw stuff on your screen will be passed to your onDraw() method in your View. So you need to make a View class first and add it in your MainActivity.
You can do that like this: First you create a class called MyView and add this code to it:
publicclassMyViewextendsView {
Bitmap bitmap;
publicMyView(Context context) {
bitmap = Bitmap.createBitmap(1920, 1080, Bitmap.Config.ARGB_8888);
Canvascanvas=newCanvas(bitmap);
Paintpaint=newPaint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);
floatleft=20;
floattop=20;
floatright=50;
floatbottom=100;
canvas.drawLine(left, top, right, bottom, paint);
}
@OverrideprotectedvoidonDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, null);
super.onDraw(canvas);
}
}
then you change the code in your onCreate() method in your MainActivity to this:
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyViewmyView=newMyView(this);
setContentView(myView);
}
Solution 2:
Create a class like this
publicclassMyViewextendsView {
publicMyView(Context context) {
super(context);
}
publicMyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
publicMyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@OverrideprotectedvoidonDraw(Canvas canvas) {
Paintpaint=newPaint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);
floatleft=20;
floattop=20;
floatright=50;
floatbottom=100;
canvas.drawLine(left, top, right, bottom, paint);
}
}
Post a Comment for "Android Canvas Drawline Not Drawing On Mainactivity"