Android PathShape not drawing path (Canvas/Java/Android Studio) - java

I'm just trying to draw a basic triangle in Android Studio but nothing is showing up when I run the program. This is my first Android program so I don't really know what I'm doing. What is wrong with it?
public class CustomDrawableView extends View {
private ShapeDrawable mDrawable;
public CustomDrawableView(Context context, Display display) {
super(context);
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
int pathWidth = screenWidth / 6;
int startWidth = screenWidth / 10;
Path path = new Path();
path.moveTo(startWidth, 0);
path.moveTo(startWidth, screenHeight / 5);
path.moveTo(screenWidth / 5, screenHeight / 5);
path.close();
mDrawable = new ShapeDrawable(new PathShape(path, screenWidth, screenHeight));
mDrawable.setDither(true);
int color = Color.parseColor("#ff74AC23");
mDrawable.getPaint().setColor(color);
mDrawable.setBounds(0, 0 , screenWidth, screenHeight);
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
}
public class MainActivity extends AppCompatActivity {
CustomDrawableView mCustomDrawableView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = getWindowManager().getDefaultDisplay();
mCustomDrawableView = new CustomDrawableView(this, display);
setContentView(mCustomDrawableView);
}
}

Related

How to set delay in draw line using canvas

am new to android platform and try to draw line with delay for each pixel. But when the execute the code they not delay each pixel they are going to display after full loop executing i don't know why to do like this. i need to some delay each pixel, i mean draw pixel to pixel in live view. it's possible please suggest sample code or example. Thanks advance.
activity
public class MainActivity extends Activity {
ImageView drawingImageView;
int x1 = 50;
int y1 = 100;
int y2 = 100;
int i;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawingImageView.setImageBitmap(bitmap);
// Line
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(5);
for (i = 0; i < 250; i++) {
try {
Thread.sleep(50);
} catch (InterruptedException ie) {
//error;
}
canvas.drawLine(x1, y1, x1 + i, y2, paint);
}
i++;
}}
Please Go through this.Hope this will work for you. :)
public class TestActivity extends AppCompatActivity {
ImageView drawingImageView;
int x1 = 50;
int y1 = 100;
int y2 = 100;
int x2=50, mCount = 1;
private Handler mHandler;
private Runnable mRunnable;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
drawingImageView.setImageBitmap(bitmap);
final Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(5);
canvas.drawLine(x1, y1, x2, y2, paint);
mHandler = new Handler(getMainLooper());
mRunnable = new Runnable() {
#Override
public void run() {
int x3 = x2 + mCount;
canvas.drawLine(x2, y1, x3, y2, paint);
x2 = x3;
mCount++;
drawingImageView.invalidate();
if (mCount < 150)
mHandler.postDelayed(mRunnable, 50);
}
};
mHandler.postDelayed(mRunnable,50);
}
}

(Android) How I get SmartPhone ScreenWidth and Height? [duplicate]

This question already has answers here:
How to Get Device Height and Width at Runtime?
(6 answers)
Closed 7 years ago.
I'm making game for Android and use SurfaceView.
I want to know SmartPhone Screen Info(Height, Width, ect..)
I uesd this code, but.. It is not correct value of display Width and Height,
It's always printed "0" by Red Color
What I miss?
public class MainActivity extends Activity {
private int width;
private int height;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
width = metrics.widthPixels;
height = metrics.heightPixels;
setContentView(new GameView(this));
}
public class Painter extends Thread
public void run(){
Canvas canvas = null;
long start, end;
int sleep;
while(true) {
if (runnable) {
start = System.currentTimeMillis();
try {
canvas = holder.lockCanvas(null);
paint.setColor(Color.RED);
paint.setTextSize(200);
synchronized (holder) {
canvas.drawText(Integer.toString(main.getHeight()), 600, 800, paint);
canvas.drawText(Integer.toString(main.getWidth()), 300, 400, paint);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
holder.unlockCanvasAndPost(canvas);
}
end = System.currentTimeMillis();
sleep = 1000 / FPS - (int) (end - start);
try {
Thread.sleep(sleep > 0 ? sleep : 0);
} // Try
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You can get it using this Code:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Works on all API versions, and therefore requires no API checking.
If you are in a view, you might need to get the context:
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);‌​
You can get Display height and width using following code.
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
/*
* A structure describing general information about a display, such as its size, density, and font scaling.
* */
DisplayMetrics metrics = getResources().getDisplayMetrics();
int DeviceTotalWidth = metrics.widthPixels;
int DeviceTotalHeight = metrics.heightPixels;
How to Get Device Height and Width at Runtime?
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width=dm.widthPixels;
int height=dm.heightPixels;
int dens=dm.densityDpi;
double wi=(double)width/(double)dens;
double hi=(double)height/(double)dens;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
double screenInches = Math.sqrt(x+y);

Why is the SurfaceView cut if I resume app?

If I use an Android L device and resume my app, the SurfaceViews are cut.
The details of occurrence condition are as follows:
- Using Android L (It is originally L, not updated to L)
- The SurfaceView is larger than the display.
- The left-top of SurfaceView is more to the left or top of the display.
- Resuming the app from the background apps list, not the icon in the app list.
I tried to reset size, gravity, clip bounds, etc., however, none had effect.
I want to repair the SurfaceView cut, you do not have some idea?
The sample code is as follows:
[Activity]
public class ViewTestActivity extends Activity {
private DrawSurfaceView mDrawSurfaceView;
private int overDispW;
private int overDispH;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point dispP = new Point();
display.getSize(dispP);
overDispW = (int) (dispP.x * 1.5);
overDispH = (int) (dispP.y * 1.5);
FrameLayout.LayoutParams overSizeParams = new FrameLayout.LayoutParams(overDispW, overDispH);
//If gravity is Gravity.LEFT|Gravity.TOP, there is no cut.
overSizeParams.gravity = Gravity.CENTER;
mDrawSurfaceView = new DrawSurfaceView(this);
setContentView(mDrawSurfaceView, overSizeParams);
}
}
[SurfaceView]
public class DrawSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private Paint mPaintRed;
private Paint mPaintBlue;
private Paint mPaintGreen;
private Paint mPaintYellow;
private SurfaceHolder mHolder;
public DrawSurfaceView(Context context) {
super(context);
mPaintRed = new Paint();
mPaintRed.setColor(Color.argb(255, 255, 0, 0));
mPaintBlue = new Paint();
mPaintBlue.setColor(Color.argb(255, 0, 0, 255));
mPaintGreen = new Paint();
mPaintGreen.setColor(Color.argb(255, 0, 255, 0));
mPaintYellow = new Paint();
mPaintYellow.setColor(Color.argb(255, 255, 255, 0));
mHolder = getHolder();
mHolder.setFormat(PixelFormat.RGBA_8888);
mHolder.addCallback(this);
}
public void onDraw(Canvas canvas){
super.onDraw(canvas);
drawRect(canvas);
}
private void drawRect(Canvas canvas) {
int w = canvas.getWidth();
int h = canvas.getHeight();
canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
canvas.drawRect(0, 0, w/2, h/2, mPaintRed);
canvas.drawRect(w/2, h/2, w, h, mPaintBlue);
canvas.drawRect(w/2, 0, w, h/2, mPaintGreen);
canvas.drawRect(0, h/2, w/2, h, mPaintYellow);
}
public void doDraw(){
Canvas canvas = mHolder.lockCanvas();
if(canvas != null){
drawRect(canvas);
mHolder.unlockCanvasAndPost(canvas);
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
doDraw();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
doDraw();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
Right side of view has been cut.

Android custom view not showing

I am working on an Android version of Gomoku. I am quite new to Java in general and even more so to Android. I am following a book called "Hello Android" where the author teaches the basics through making a game of Sudoku. I am following it loosely, leaving out features not needed for my Gomoku. However, a new view is made when New Game is pressed and although the book continues on as if it should be working, what should be drawn is not showing for me at all. Here is the code that deals with the stuff:
Mainactivity.java:
private void startGame() {
Log.d(TAG, "Clicked New Game");
Intent intent = new Intent(this, Game.class);
startActivity(intent);
}
Game.java:
public class Game extends Activity {
private static final String TAG = "Game";
private int board[] = new int[10 * 10];
private GameView gameView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Game.onCreate called");
gameView = new GameView(this);
gameView.requestFocus();
Log.d(TAG, "Game.onCreate finished");
}
}
GameView.java:
public class GameView extends View {
private static final String TAG = "Game";
private float width; //Width of one tile
private float height; //Height of one tile
private final Game game;
Paint background = new Paint();
Paint dark = new Paint();
Paint light = new Paint();
Paint hilite = new Paint();
public GameView(Context context) {
super(context);
this.game = (Game) context;
setFocusable(true);
setFocusableInTouchMode(true);
Log.d(TAG, "GameView finished");
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w / 10f;
height = h /10f;
Log.d(TAG, "onSizeChanged: width " + width + ", height " + height);
}
#Override
protected void onDraw(Canvas canvas) {
//Draw the background
background.setColor(getResources().getColor(R.color.background));
canvas.drawRect(0, 0, getWidth(), getHeight(), background);
//Draw the board
//Define colors for grid lines
dark.setColor(getResources().getColor(Color.DKGRAY));
light.setColor(getResources().getColor(Color.LTGRAY));
hilite.setColor(getResources().getColor(Color.WHITE));
for (int i = 0; i < 10; i++) {
Log.d(TAG, "Drawing...");
canvas.drawLine(0, i * height - 1, getWidth(), i * height - 1, light);
canvas.drawLine(0, i * width - 1, getHeight(), i * width - 1, light);
canvas.drawLine(0, i * height, getWidth(), i * height, hilite);
canvas.drawLine(0, i * width, getHeight(), i * width, hilite);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1, dark);
canvas.drawLine(0, i * width + 1, getHeight(), i * width + 1, dark);
}
}
}
I have tried comparing the author's code to mine and except where I am not implementing features he is the codes seem to be matching.
However, the Log.d(TAG, "onSizeChanged: width " + width + ", height " + height); does not appear in LogCat so I assume this function is simply never called and I do not understand why.
You just create an instance of your GameView but you do not add it to your activity. Do this by using
setContentView(gameView);
in your onCreate method.
You need to set the view to the activity with setContentView(gameView) in onCreate of Game Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Game.onCreate called");
gameView = new GameView(this);
setContentView(gameView); // missing
...//rest of the code

How can I center this rectangle and image in the y axis?

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();

Categories

Resources