Cannot determine screen size in onDraw? - General Questions and Answers

Hi!
I have written a test program that just draws a cross on the screen.
I have a webpage on a server with the hostname darkbox.dyndns.org. There is a directory called test on it. Now you can conclude the url to the directory where I have put the demonstration files for this question.
The TestActivity.java file shows how I try to draw the cross.
You can see different screenshots. When I try it on my phone, it seems that I dont have access to the full screen or something. Or how should I do this properly?
I got an error message when I tried to post the link. it reads like this:
"To prevent spam to the forums, ALL new users are not permitted to post outside links in their messages. After approximately eight posts, you will be able to post outside links. Thanks for understanding!"
Thats why I could not post the link
/best regards
purginator

The source
A bit easier if I give you the source instead of just giving you the url to it.
Here is comes (TestActivity.java).
package testing.testing;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TableLayout.LayoutParams;
public class TestActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags
(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new the_view(this));
}
private class the_view extends View
{
public the_view(Context context)
{
super(context);
setLayoutParams
(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
@Override
public void onDraw(Canvas canvas)
{
int width = canvas.getWidth();
int height = canvas.getHeight();
Paint paint = new Paint();
paint.setColor(0xffc0c0c0);
float[] points1 =
{
0, 0, width, 0,
width, 0, width, height,
width, height, 0, height,
0, height, 0, 0
};
float[] points2 = { 0,0, width, height };
float[] points3 = { width,0, 0, height };
paint.setStrokeWidth(10);
canvas.drawLines(points1, paint);
paint.setStrokeWidth(5);
canvas.drawLines(points2, paint);
canvas.drawLines(points3, paint);
}
}
}

I think size of the view can be determed wrong there:
Code:
int width = canvas.getWidth();
int height = canvas.getHeight();
Try to add this to your the_view class:
Code:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
invalidate();
}
It looks like your onDraw method is called only once with incorrect width and height because view doesn't still fill the parent layout. The code above will force it to redraw on any size change.

Does not work, the same behaviour

The idea is that you shouldn't use canvas size directly like this:
Code:
int width = canvas.getWidth();
int height = canvas.getHeight();
But should use view's size:
Code:
int width = getWidth();
int height = getHeight();

Solution found
All I had was to target a higher API version than 1.5.
I used 2.1 and I could use the whole screen.
So do never recommend people to use 1.5, as I was recommended!

Related

[Q] Probably easy but...accelerometer and random generator

Trying to use a random image generator as an action if accelerometer is utilized....different image each time the phone is shook.
import java.util.Random;
import android.app.Activity;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
public class ShakeActivity extends Activity implements SensorListener {
// For shake motion detection.
private SensorManager sensorMgr;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 800;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// start motion detection
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
boolean accelSupported = sensorMgr.registerListener(this,
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
if (!accelSupported) {
// on accelerometer on this device
sensorMgr.unregisterListener(this,
SensorManager.SENSOR_ACCELEROMETER);
}
}
protected void onPause() {
if (sensorMgr != null) {
sensorMgr.unregisterListener(this,
SensorManager.SENSOR_ACCELEROMETER);
sensorMgr = null;
}
super.onPause();
}
public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(int sensor, float[] values) {
Log.d("sensor", "onSensorChanged: " + sensor);
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// only allow one update every 100ms.
if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
x = values[SensorManager.DATA_X];
y = values[SensorManager.DATA_Y];
z = values[SensorManager.DATA_Z];
float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;
// Log.d("sensor", "diff: " + diffTime + " - speed: " + speed);
if (speed > SHAKE_THRESHOLD) {
ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
}
Thanks in advance for help?

[Q][DEV]Android Development Maps Question

I'm trying to develop (for the liveview) using an SDK and need to get a bitmap of Google Maps.
Code:
//Map Section
public class myMap extends MapActivity {
MapView mapView;
Bitmap bitmap;
boolean created = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createMap();
}
public void createMap()
{
// build map and mark point
mapView = new MapView(this, "keykeykeykeykeykey");
mapView.setBuiltInZoomControls(false);
GeoPoint point = new GeoPoint(52242730,-884211);
mapView.getController().animateTo(point);
mapView.preLoad();
// copy MapView to canvas
bitmap = Bitmap.createBitmap(400, 800, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
mapView.draw(canvas);
PluginUtils.sendTextBitmap(mLiveViewAdapter, mPluginId, "Loading Map...", 128, 12);
created = true;
}
public void displayMap()
{
if (created == false)
{
createMap();
}
//Display map on device
Bitmap mybit = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888);
for(int i = 0; i < 128; i++)
{
for(int j = 0; j < 128; j++)
{
mybit.setPixel(i, j, bitmap.getPixel(i, j));
}
}
//white pixel for debugging
mybit.setPixel(64, 64, Color.WHITE);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Is what I've got so far, the code in createMap() was in onCreate() but It didn't seem to be called.
Now it just force closes.
Anyone know how to help? Is there a better place to ask development questions?
Thanks.
-=Edit=-
Oh, and here's the routine calling the map thing, every couple of seconds.
Code:
private class Timer implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
myMap theMap = new myMap();
theMap.displayMap();
}
}
Okay, looks like you cant use google street map like this.
Anyone looking for similar solution, I used open street map and downloaded 'slipery tiles' png's. They provide java routines for finding the tile url from lat/lon.
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames

HELP - Image Gallery In gridview to display images from spicifc folder on sdcard

I have done a lot of searching and I have come up with this code to try and display images that are located in a Folder on my SDCard. The folder is located at /.data/ToDo/.nomedia/ (I am trying to hide this images from the Main Android Gallery) The Code seems to run fine, i don't get any errors, but it's just not displaying the images. I was hoping someone could tell me what I am missing. Any Help would be greatly appreciated!!
Here is my GalleryActivity
Code:
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryActivity extends Activity {
/** Called when the activity is first created. */
private Cursor imagecursor, actualimagecursor, cursor;
private int image_column_index, actual_image_column_index;
File sdCardDir = Environment.getExternalStorageDirectory(); //SDCard Location
String imagesDir = ("sdCardDir" + "/.data/ToDo/.nomedia/"); //Path to Images
GridView imagegrid;
private int count;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
init_phone_image_grid();
}
private void init_phone_image_grid() {
String[] img = { MediaStore.Images.Media._ID };
imagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, img, MediaStore.Images.Media.DATA + " like ? ", new String[] {imagesDir}, null);
image_column_index = imagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
count = imagecursor.getCount();
imagegrid = (GridView) findViewById(R.id.sdcard);
imagegrid.setAdapter(new ImageAdapter(getApplicationContext()));
imagegrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
System.gc();
String[] proj = { MediaStore.Images.Media.DATA };
actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj,null, null, null);
actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToPosition(position);
String i = actualimagecursor.getString(actual_image_column_index);
System.gc();
Intent intent = new Intent(getApplicationContext(), GalleryFlow.class);
intent.putExtra("filename", i);
startActivity(intent);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
System.gc();
ImageView i = new ImageView(mContext.getApplicationContext());
if (convertView == null) {
imagecursor.moveToPosition(position);
int id = imagecursor.getInt(image_column_index);
int imageID = 0;
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
// Set the content of the image based on the image URI
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
//i.setImageURI(Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID)));
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
}
else {
i = (ImageView) convertView;
}
return i;
}
}
}

[App] [Tutorial] Learn to make a Compass Application

Hello,
I create this post to present you a video tutorial showing you how to create a compass application for Android steps by steps. This tutorial lets beginners to start with sensors on Android and also to discover how to get GPS Location with default Android services.
Tutorial is here :
A demo application is also available on Google Play Store : https://play.google.com/store/apps/details?id=com.ssaurel.tinycompass
Don't hesitate to tell me if you want more details about the source code.
Sylvain
Compass View source code
Hello,
To start with source code, this is CompassView source code :
Code:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import com.ssaurel.tinycompass.R;
/**
* Compass view.
*
* @author Sylvain Saurel - [email protected]
*
*/
public class CompassView extends View {
private static final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int width = 0;
private int height = 0;
private Matrix matrix;
private Bitmap bitmap;
private float bearing;
public CompassView(Context context) {
super(context);
initialize();
}
public CompassView(Context context, AttributeSet attr) {
super(context, attr);
initialize();
}
private void initialize() {
matrix = new Matrix();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.compass_icon);
}
public void setBearing(float bearing) {
this.bearing = bearing;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec);
height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
if (bitmap.getWidth() > canvasWidth || bitmap.getHeight() > canvasHeight) {
// resize to fit canvas
bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmapWidth * .85), (int) (bitmapHeight * .85), true);
}
// calculate center position
int bitmapX = bitmap.getWidth() / 2;
int bitmapY = bitmap.getHeight() / 2;
int parentX = width / 2;
int parentY = height / 2;
int centerX = parentX - bitmapX;
int centerY = parentY - bitmapY;
// rotation angle
int rotation = (int) (360 - bearing);
// transformation matrix
matrix.reset();
// rotate on center to put on North
matrix.setRotate(rotation, bitmapX, bitmapY);
// translate bitmap to center
matrix.postTranslate(centerX, centerY);
// draw bitmap
canvas.drawBitmap(bitmap, matrix, paint);
}
}
Don't hesitate if you have comments .
Sylvain
Hello,
A blog article to complete the video tutorial is also available now : http://www.ssaurel.com/blog/learn-how-to-make-a-compass-application-for-android/
Sylvain

Google Vision: Drawing mask on Face with animations

I am using google vision library for face detection. Face detection is perfect and I get all the info like vertices, angles like eulerY, eulerZ.
I want to draw mask on face, drawing is ok but the face mask is not following the face position as it should, the position is not correct. Here is my edited code to draw face mask on googly eyes project.
Here is my source code:
package com.google.android.gms.samples.vision.face.googlyeyes;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.android.gms.samples.vision.face.googlyeyes.ui.camera.GraphicOverlay;
import com.google.android.gms.vision.face.Face;
import java.util.HashMap;
/**
* Graphics class for rendering Googly Eyes on a graphic overlay given the current eye positions.
*/
class GooglyEyesGraphic extends GraphicOverlay.Graphic {
private Paint mEyeWhitesPaint;
private Paint mEyeIrisPaint;
private Paint mEyeOutlinePaint;
private Paint mEyeLidPaint;
Paint mBoxPaint;
Context mContext;
private static final float BOX_STROKE_WIDTH = 20.0 f;
FrameLayout frameLayout;
ImageView imageView;
// Bitmap bmpOriginal;
//==============================================================================================
// Methods
//==============================================================================================
GooglyEyesGraphic(GraphicOverlay overlay, Context mContext) {
super(overlay);
this.mContext = mContext;
mEyeWhitesPaint = new Paint();
mEyeWhitesPaint.setColor(Color.WHITE);
mEyeWhitesPaint.setStyle(Paint.Style.FILL);
mEyeLidPaint = new Paint();
mEyeLidPaint.setColor(Color.YELLOW);
mEyeLidPaint.setStyle(Paint.Style.FILL);
mEyeIrisPaint = new Paint();
mEyeIrisPaint.setColor(Color.BLACK);
mEyeIrisPaint.setStyle(Paint.Style.FILL);
mEyeOutlinePaint = new Paint();
mEyeOutlinePaint.setColor(Color.BLACK);
mEyeOutlinePaint.setStyle(Paint.Style.STROKE);
mEyeOutlinePaint.setStrokeWidth(5);
mBoxPaint = new Paint();
mBoxPaint.setColor(Color.MAGENTA);
mBoxPaint.setStyle(Paint.Style.STROKE);
mBoxPaint.setStrokeWidth(BOX_STROKE_WIDTH);
mBoxPaint.setAlpha(40);
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.mask_layout, null);
imageView = (ImageView) view.findViewById(R.id.flMaskIV);
frameLayout = (FrameLayout) view.findViewById(R.id.frameLayout);
}
private volatile Face mFace;
/**
* Updates the eye positions and state from the detection of the most recent frame. Invalidates
* the relevant portions of the overlay to trigger a redraw.
*/
void updateEyes(PointF leftPosition, boolean leftOpen,
PointF rightPosition, boolean rightOpen, Face mFace) {
if (facesList.containsKey(mFace.getId())) {
PointF pointF1 = facesList.get(mFace.getId()).getPosition();
PointF pointF2 = mFace.getPosition();
double x = Math.sqrt(Math.pow(pointF2.x - pointF1.x, 2) - Math.pow(pointF2.y - pointF1.y, 2));
if (x < 0)
x = (-1 * x);
if (x < 10)
return;
Log.e("face Called", "FaceCalled");
}
this.mFace = mFace;
facesList.put(mFace.getId(), mFace);
postInvalidate();
}
public HashMap < Integer, Face > facesList = new HashMap < > ();
/**
* Draws the current eye state to the supplied canvas. This will draw the eyes at the last
* reported position from the tracker, and the iris positions according to the physics
* simulations for each iris given motion and other forces.
*/
@override
public void draw(Canvas canvas) {
if (mFace == null)
return;
// if (facesList.containsKey(mFace.getId())) {
// PointF pointF1 = facesList.get(mFace.getId()).getPosition();
// PointF pointF2 = mFace.getPosition();
//
// double x = Math.sqrt(Math.pow(pointF2.x - pointF1.x, 2) - Math.pow(pointF2.y - pointF1.y, 2));
// if (x < 0)
// x = (-1 * x);
// if (x < 10)
// return;
// Log.e("face Called", "FaceCalled");
//
// }
//
// facesList.put(mFace.getId(), mFace);
if (this.canvas == null)
this.canvas = canvas;
applyMask();
}
Drawable drawable;
Canvas canvas;
private void applyMask() {
if (canvas == null)
return;
// Log.e("mFace.getEulerY()", "mFace.getEulerY()=> " + mFace.getEulerY());
if (GooglyEyesActivity.maskImgView != null) {
GooglyEyesActivity.maskImgView.setVisibility(View.GONE);
GooglyEyesActivity.maskImgView.setImageResource(GooglyEyesActivity.currEmoticonID);
}
float x = translateX(mFace.getPosition().x + mFace.getWidth() / 2);
float y = translateY(mFace.getPosition().y + mFace.getHeight() / 2);
// Draws a bounding box around the face.
float xOffset = scaleX(mFace.getWidth() / 2.0 f);
float yOffset = scaleY(mFace.getHeight() / 2.0 f);
float left = x - xOffset - 50;
float top = y - (yOffset) - 50;
float right = x + xOffset + 50;
float bottom = y + (yOffset) + 50;
// canvas.drawRect((int) left, (int) top, (int) right, (int) bottom, mBoxPaint);
drawable = GooglyEyesActivity.maskImgView.getDrawable();
///////////////////
canvas.save();
canvas.translate(left, top);
// frameLayout.setX(left);
// frameLayout.setY(top);
Rect rect = new Rect((int) left, (int) top, (int) right, (int) bottom);
frameLayout.measure(rect.width(), rect.height());
frameLayout.setLayoutParams(new LinearLayout.LayoutParams(rect.width(), rect.height()));
frameLayout.layout(0, 0, (int) right, (int) bottom);
frameLayout.setClipBounds(rect);
imageView.setLayoutParams(new FrameLayout.LayoutParams(rect.width(), rect.height()));
imageView.setRotationY(mFace.getEulerY());
imageView.setRotation(mFace.getEulerZ());
imageView.setImageDrawable(drawable);
frameLayout.draw(canvas);
canvas.restore();
}
}
Also i need to add animations so i tried using dlib library to get landmarks points and draw it using opengl but in opengl i dont have any function to populate the vertice array i am getting from dlib. As the dlib landmarks are in points but the array there is not in such a way. Any help will be appreciated for both scenarios.
Thank you in advance.
Thanks.
aijaz070110 said:
I am using google vision library for face detection. Face detection is perfect and I get all the info like vertices, angles like eulerY, eulerZ.
I want to draw mask on face, drawing is ok but the face mask is not following the face position as it should, the position is not correct. Here is my edited code to draw face mask on googly eyes project.
Here is my source code:
[...]
Also i need to add animations so i tried using dlib library to get landmarks points and draw it using opengl but in opengl i dont have any function to populate the vertice array i am getting from dlib. As the dlib landmarks are in points but the array there is not in such a way. Any help will be appreciated for both scenarios.
Thank you in advance.
Thanks.
Click to expand...
Click to collapse
Do you have any progress on this?

Categories

Resources