Android - multiple draw on ImageView - android

I'm new in Android and I have a problem with my app: I have a layout with an ImageView and more EditTexts and Buttons. I'm trying to draw a circle on the Image View every time I input coordinates in a EditText and push a button.
I found a way to make it work the first time, but if I just copy the same code for the 2nd button it draws the new circle and erases the first one. And I want to have both of them...
Somebody can tell me whet I do wrong? Thanks a lot.
My activity:
public class IndoorPositioningMainActivity extends Activity {
Button InitialPos = null;
Button P1 = null;
EditText InitialPosX = null;
EditText InitialPosY = null;
EditText InitialPosZ = null;
EditText P1X = null;
EditText P1Y = null;
EditText P1Z = null;
ImageView Image = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_indoor_positioning_main);
InitialPos = (Button)findViewById(R.id.ButtonInitialPosInput);
P1 = (Button)findViewById(R.id.ButtonP1);
InitialPosX = (EditText)findViewById(R.id.InitialPosInputX);
InitialPosY = (EditText)findViewById(R.id.InitialPosInputY);
InitialPosZ = (EditText)findViewById(R.id.InitialPosInputZ);
P1X = (EditText)findViewById(R.id.P1InputX);
P1Y = (EditText)findViewById(R.id.P1InputY);
P1Z = (EditText)findViewById(R.id.P1InputZ);
Image = (ImageView)findViewById(R.id.imageView1);
InitialPos.setOnClickListener(InitialPosListener);
P1.setOnClickListener(P1Listener);
InitialPosX.addTextChangedListener(textWatcher);
InitialPosY.addTextChangedListener(textWatcher);
InitialPosZ.addTextChangedListener(textWatcher);
P1X.addTextChangedListener(textWatcher);
P1Y.addTextChangedListener(textWatcher);
P1Z.addTextChangedListener(textWatcher);
new PositionAsync().execute();
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
};
private OnClickListener InitialPosListener = new OnClickListener() {
#Override
public void onClick(View v) {
String x = InitialPosX.getText().toString();
String z = InitialPosZ.getText().toString();
float x0 = Float.valueOf(x);
float z0 = Float.valueOf(z);
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.est,myOptions);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(x0, z0, 50, paint);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap);
}
};
private OnClickListener P1Listener = new OnClickListener() {
#Override
public void onClick(View v) {
String x11 = P1X.getText().toString();
String z11 = P1Z.getText().toString();
float x1 = Float.valueOf(x11);
float z1 = Float.valueOf(z11);
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.est,myOptions);
Paint paint1 = new Paint();
paint1.setAntiAlias(true);
paint1.setColor(Color.BLUE);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(x1, z1, 25, paint1);
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(mutableBitmap);
}
};
//XML READER
class PositionAsync extends AsyncTask<Void, Void, Void> {
XMLHelper helper;
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
my xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10px" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="70"
android:adjustViewBounds="true"
android:cropToPadding="false"
android:scaleType="centerInside"
android:src="#drawable/est" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:layout_weight="30"
android:orientation="vertical"
android:padding="10px" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/InitialPosX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" />
<EditText
android:id="#+id/InitialPosInputX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/InitialPosY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y" />
<EditText
android:id="#+id/InitialPosInputY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/InitialPosZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z" />
<EditText
android:id="#+id/InitialPosInputZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<Button
android:id="#+id/ButtonInitialPosInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/P1X"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X" />
<EditText
android:id="#+id/P1InputX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/P1Y"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y" />
<EditText
android:id="#+id/P1InputY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/P1Z"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z" />
<EditText
android:id="#+id/P1InputZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
<Button
android:id="#+id/ButtonP1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
</LinearLayout>

Firstly I suppose that "#drawable/est" is the basic image that will be painted. Then Every time that the button is clicked "est" image is reopened so the previous circles aren't saved.
One possible solution is to use a SurfaceView. There are many tutorials on internet about it.
Other solution is not to load "est" image every time, instead of that try saving the canvas and draw the circles one after another.
Hope it helps

The problem is that you only draw 1 circle in your OnClickListener(), and you draw it on a bitmap that you read from a file every time.
Instead you should save the coordinates into a list, and in the click listener draw all the circles from the list.
Like this:
String x11 = P1X.getText().toString();
String z11 = P1Z.getText().toString();
float x1 = Float.valueOf(x11);
float z1 = Float.valueOf(z11);
points.add(new Point(x1, z1));
And then:
for (Point point : points) {
canvas.drawCircle(point.x, point.y, 25, paint1);
}

Related

"Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference " error in my android app [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
My English is not so good, but I will try..
I am having a problem with my android app (obesity measurement app).
In AVD (android virtual device), my app works well.
But, on my smartphone (Galaxy S7) my app causes an error.
Error massage is
" BMI calcu keeps stopping " .
('BMI calcu' is the name of App.)
What should I do?
Please give me a hand...
<<<< Layout file >>>>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="comp.whcomp.whteam.bmicalcu.MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="BMI calculator"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="height : " />
<EditText
android:id="#+id/heightEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="number|numberDecimal"
android:maxLength="5" />
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="cm" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="weight : " />
<EditText
android:id="#+id/weightEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="number|numberDecimal"
android:maxLength="5" />
<TextView
android:id="#+id/textView4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="kg" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/textView5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="BMI : " />
<TextView
android:id="#+id/bmiTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView6"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
<comp.whcomp.whteam.bmicalcu.BmiView
android:id="#+id/BmiView2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="6"
android:orientation="horizontal"></LinearLayout>
</LinearLayout>
Main code is as following:
MainActivity.java
public class MainActivity extends Activity {
EditText mWeightEditText;
EditText mHeightEditText;
TextView mBmiTextView;
float floatWeight;
float floatHeight;
static float floatBmi = 0f;
String strBmi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mWeightEditText = (EditText)findViewById(R.id.weightEditText);
mHeightEditText = (EditText)findViewById(R.id.heightEditText);
mBmiTextView = (TextView)findViewById(R.id.bmiTextView);
mWeightEditText.addTextChangedListener(mWatcher);
mHeightEditText.addTextChangedListener(mWatcher);
} // end of onCreate()
TextWatcher mWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence,int i,int i1,int i2){}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2){
if((mWeightEditText.getText().toString().length()>0) &&
(mHeightEditText.getText().toString().length()>0)) {
if(mHeightEditText.getText().toString().equals("0")){
} else {
floatWeight=Float.parseFloat(mWeightEditText.getText().toString());
floatHeight=Float.parseFloat(mHeightEditText.getText().toString());
floatBmi=(floatWeight/(floatHeight/100f)) / (floatHeight/100f);
strBmi = String.format("%.1f", floatBmi);
mBmiTextView.setText(strBmi);
}
} else {
mBmiTextView.setText("");
floatBmi = 0f;
}
} // end of onTextchange()
#Override
public void afterTextChanged(Editable editable) {}
}; // end of TextWatcher
}
BmiView.java
public class BmiView extends SurfaceView implements SurfaceHolder.Callback {
Context mContext;
private BmiThread mThread;
int screenWidth;
int screenHeight;
int radius;
int xOfCenterOfCircle;
int yOfCenterOfCircle;
int tOfRectOfArc;
int bOfRectOfArc;
int lOfRectOfArc;
int rOfRectOfArc;
int xOfNeedleEnd = 0;
int yOfNeedleEnd = 0;
int intBmi;
RectF rect;
private Paint mPaintGreen;
private Paint mPaintBlack;
private Paint mPaintNeedle;
// constructor
public BmiView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
mContext = context;
mPaintGreen = new Paint();
mPaintBlack = new Paint();
mPaintNeedle = new Paint();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
screenWidth = w;
screenHeight = h;
if ( h > w/2 ) {
radius = w*4/10;
} else {
radius = h*4/5;
}
xOfCenterOfCircle = w/2;
yOfCenterOfCircle = h*4/5;
tOfRectOfArc = yOfCenterOfCircle - radius;
bOfRectOfArc = yOfCenterOfCircle + radius;
lOfRectOfArc = xOfCenterOfCircle - radius;
rOfRectOfArc = xOfCenterOfCircle + radius;
mPaintGreen.setColor(Color.GREEN);
mPaintBlack.setColor(Color.BLACK);
mPaintNeedle.setColor(Color.RED);
mPaintNeedle.setStrokeWidth(10);
rect = new RectF();
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
mThread = new BmiThread(surfaceHolder);
mThread.setRunning(true);
mThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder,int i,int i1,int i2){}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
boolean retry = true;
mThread.setRunning(false); // terminate mThread
while (retry) {
try {
mThread.join(); // wait for mThread to finish
retry = false;
}
catch (InterruptedException e) {}
}
}
class BmiThread extends Thread {
private SurfaceHolder surfaceHolder;
private boolean threadIsRunning = true; // running by default
public BmiThread(SurfaceHolder holder) {
surfaceHolder = holder;
}
public void setRunning (boolean running) {
threadIsRunning = running;
}
public void run() {
Canvas canvas = null;
while (threadIsRunning) {
try {
canvas = surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
canvas.drawColor(Color.WHITE);
rect.set(lOfRectOfArc, tOfRectOfArc, rOfRectOfArc, bOfRectOfArc);
canvas.drawArc(rect, 180, 180, false, mPaintGreen);
intBmi = (int)MainActivity.floatBmi;
if(intBmi > 40) {
intBmi = 40;
}
double deg = 180*(intBmi/40d), rad;
rad = Math.toRadians(deg);
xOfNeedleEnd = xOfCenterOfCircle - (int)(( Math.cos(rad) )*radius);
yOfNeedleEnd = yOfCenterOfCircle - (int)(( Math.sin(rad) )*radius);
canvas.drawLine(xOfCenterOfCircle, yOfCenterOfCircle, xOfNeedleEnd,
yOfNeedleEnd, mPaintNeedle);
canvas.drawCircle(xOfCenterOfCircle, yOfCenterOfCircle, 10,
mPaintBlack);
}
} finally {
if (canvas != null)
surfaceHolder.unlockCanvasAndPost(canvas);
}
} // end of while()
} // end of run()
} // end of thread.
}
<<<< Logcat message >>>>
08-02 16:00:18.127 3086-3213/comp.whcomp.whteam.bmicalcu E/AndroidRuntime: FATAL EXCEPTION: Thread-7
Process: comp.whcomp.whteam.bmicalcu, PID: 3086
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Canvas.drawColor(int)' on a null object reference
at comp.whcomp.whteam.bmicalcu.BmiView$BmiThread.run(BmiView.java:123)
Check that you are creating an instance before trying to set the colour. It is complaining because the object you're trying to set the colour for doesn't exist at the time you're trying to set it.
Hmm. For the first glance, your code seems correct. Maybe is because your BmiView has a height of 0dp? - see the layout

Android Matrix postRotate and postTranslate applied to a Bitmap

Here is a code snippet which I wrote trying to understand Matrix (postRotate and postTranslate to be more exact).
Activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView mImageView2;
#Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.btn:
Matrix matrix = new Matrix();
matrix.postRotate(90);
matrix.postTranslate(200, 0);
Bitmap bitmap =
BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher, null);
Bitmap bitmap2 = Bitmap.createBitmap(
bitmap,
0,
0,
bitmap.getWidth(),
bitmap.getHeight(),
matrix,
true
);
mImageView2.setImageBitmap(bitmap2);
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(this);
mImageView2 = (ImageView) findViewById(R.id.image2);
}
}
XML layout:
<?xml version="1.0" encoding="utf-8"?>
<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="vertical"
tools:context="sample2.com.sample_app.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<ImageView
android:id="#+id/image2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ccc"
android:scaleType="matrix"
tools:src="#mipmap/ic_launcher" />
</LinearLayout>
The problem is that the bitmap is rotated but not moved anywhere:
What am I doing wrong?

How to re-scale Bitmap image size?

Hi guys I am trying to load a image from a url and after loading that i am trying to re scale it such that it fits the whole screen after that the text and the buttons present are available below the image which are wrapped around using scroll view
this is my fragment
public class FirstFragment extends Fragment {
ImageView im;
Bitmap bitmap;
Drawable dr;
Bitmap bitap;
Bitmap newBitmap;
RelativeLayout rel;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.first_frag, container, false);
rel = (RelativeLayout) v.findViewById(R.id.relativla);
rel.setVisibility(View.INVISIBLE);
new LoadImage().execute("http://opinions.esy.es/bg.jpg");
Button b = (Button) v.findViewById(R.id.navi);
im = (ImageView) v.findViewById(R.id.imageView);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), Navi.class);
startActivity(i);
}
});
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
dr = new BitmapDrawable(getResources(),image);
bitap = ((BitmapDrawable) dr).getBitmap();
float scalingFactor = getBitmapScalingFactor(bitap);
Bitmap newBitmap = Util.ScaleBitmap(bitmap, scalingFactor);
im.setImageBitmap(newBitmap);
}else{
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
private float getBitmapScalingFactor(Bitmap bm) {
Toast.makeText(getContext(),"entered here",Toast.LENGTH_LONG).show();
// Get display width from device
int displayWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
// Get margin to use it for calculating to max width of the ImageView
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)this.im.getLayoutParams();
int leftMargin = layoutParams.leftMargin;
int rightMargin = layoutParams.rightMargin;
// Calculate the max width of the imageView
int imageViewWidth = displayWidth - (leftMargin + rightMargin);
rel.setVisibility(View.VISIBLE);
// Calculate scaling factor and return it
return ( (float) imageViewWidth / (float) bm.getWidth() );
}
}
My Util class
public class Util {
public static Bitmap ScaleBitmap(Bitmap bm, float scalingFactor) {
int scaleHeight = (int) (bm.getHeight() * scalingFactor);
int scaleWidth = (int) (bm.getWidth() * scalingFactor);
return Bitmap.createScaledBitmap(bm, scaleWidth, scaleHeight, true);
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:fillViewport="true"
>
<RelativeLayout
android:id="#+id/relativla"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/hamburger"
android:id="#+id/navi"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:id="#+id/imageView"
android:scaleType="fitCenter"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Diet Plans"
android:padding="10dp"
android:layout_marginTop="10dp"
android:textColor="#android:color/black"
android:textSize="25sp"
android:id="#+id/textView5"
android:layout_below="#+id/imageView"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/descrpitiondietplan"
android:textColor="#000000"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textSize="15sp"
android:padding="10dp"
android:id="#+id/textView6"
android:layout_below="#+id/textView5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Our Diet Plans"
android:textColor="#android:color/black"
android:padding="10dp"
android:textSize="25sp"
android:id="#+id/textView7"
android:layout_below="#+id/textView6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:padding="10dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Basic Diet Plan"
android:textColor="#android:color/white"
android:id="#+id/normmal"
android:background="#color/btn_login"
android:layout_marginBottom="10dp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
It the toast insider the getBitmapScaling factor is called after the relative layout is viewed
Hope you guys can help me solve my issue
try add these
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(dm.widthPixels, dm.heightPixels);
im.setLayoutParams(params);
below im.setImageBitmap(newBitmap); onPostExecute

Draw and animate a dashed line

I have a fullscreen activity that should look like this:
where the big white circle would have some text, I've already done it, but the problem is that I don't know how to do that dashed lines between the icons, also they want a little animation in the icons, so I assumed that each one should be a separate view, so far I've done this (it doesn't need to look exactly the same):
So, how could I draw that lines? Also if I could make that dashes to "run" acrross the lines would be awesome.
this is my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rlt_welcome"
android:layout_weight="9"
android:background="#drawable/bg"
>
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="2"
android:orientation="vertical"
android:padding="10dp"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:id="#+id/img_youtube"
android:src="#drawable/youtube_circle"
android:layout_marginTop="60dp"
android:layout_marginRight="60dp"
android:layout_height="wrap_content"
/>
<ImageView
android:layout_width="wrap_content"
android:src="#drawable/tablet_circle"
android:layout_height="wrap_content"
android:layout_above="#+id/img_stats"
android:layout_marginRight="30dp"
android:layout_below="#+id/img_youtube"
/>
<ImageView
android:layout_width="wrap_content"
android:id="#+id/img_stats"
android:src="#drawable/stats_circle"
android:layout_height="wrap_content"
android:layout_marginRight="70dp"
android:layout_marginBottom="20dp"
android:layout_alignParentBottom="true"/>
<ImageView
android:id="#+id/img_iphone"
android:layout_width="wrap_content"
android:src="#drawable/iphone_circle"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
/>
<ImageView
android:layout_width="wrap_content"
android:src="#drawable/imac_circle"
android:layout_height="wrap_content"
android:layout_below="#+id/img_iphone"
android:layout_marginLeft="70dp"
android:layout_marginTop="-30dp"
/>
<ImageView
android:layout_width="wrap_content"
android:src="#drawable/webcam_circle"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="5"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:padding="40dp"
android:textSize="25sp"
android:textColor="#color/text1"
android:layout_margin="20dp"
android:text="Bienvenido"
android:background="#drawable/flat_circle"
android:id="#+id/txt_welcome"
android:layout_centerInParent="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/arrow_circle"
android:id="#+id/img_arrow"
android:layout_alignParentTop="true"
android:layout_marginRight="60dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/news_circle"
android:layout_below="#+id/img_arrow"
android:layout_marginTop="-90dp"
android:layout_marginRight="2dp"
android:layout_marginLeft="70dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/line_circle"
android:id="#+id/img_line"
android:layout_below="#+id/img_arrow"
android:layout_marginTop="-10dp"
android:layout_marginRight="70dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/money_circle"
android:layout_below="#+id/img_line"
android:layout_marginRight="6dp"
android:layout_marginTop="-70dp"
android:layout_marginLeft="70dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/mouse_circle"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginRight="80dp"
/>
</RelativeLayout>
</LinearLayout>
Please check this, may be this will help you
http://www.rengelbert.com/tutorial.php?id=182
How do I get this work, I made a new activity that holds a Canvas controller, and place the bitmaps on the canvas and draw the lines between them with this, I didn't use any external library:
Hope someone could reuse some code and not only been told to google it.
MainActivty.java
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeMainActivity = (RelativeLayout) findViewById(R.id.rlt_main);
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
final int heightS = dm.heightPixels;
final int widthS = dm.widthPixels;
Log.d("MainActvitiy", "widht:" + widthS);
myPanel = new Panel(getApplicationContext(),this,widthS, heightS);
relativeMainActivity.addView(myPanel);
RelativeLayout RR = new RelativeLayout(this);
RR.setGravity(Gravity.CENTER);
relativeMainActivity.addView(RR,400,150);
RR.setX(0);
LayoutInflater myInflater = (LayoutInflater) getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
}
Panel.java
public class Panel extends SurfaceView implements SurfaceHolder.Callback {
public MainThread thread;
private Background background;
private CircleManager CM;
public int ScreenWidth;
public int Screenheigt;
private CircleIcon icon1;
private CircleIcon icon2;
private CircleIcon icon3;
//and so on
public MainActivity myMain;
public Panel(Context context, MainActivity _main, int width , int height) {
super(context);
getHolder().addCallback(this);
this.myMain = _main;
this.ScreenWidth=width;
this.Screenheigt=height;
thread = new MainThread(getHolder(),this);
background = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.bg), Screenheigt, this);
CM = new CircleManager( this,context,ScreenWidth);
CM.setScreen(ScreenWidth, Screenheigt);
SetIcons();
CM.setManager();
setFocusable(true);
}
void SetIcons()
{
icon1 = new CircleIcon(BitmapFactory.decodeResource(getResources(),R.drawable.circle_iphone),39,40);
icon2 = new CircleIcon(BitmapFactory.decodeResource(getResources(),R.drawable.circle_chat),280,40);
icon3 = new CircleIcon(BitmapFactory.decodeResource(getResources(),R.drawable.circle_youtube),60,200);
//and so on
icon1.myConnections.add(2);
icon1.myConnections.add(3);
icon2.myConnections.add(15);
icon3.myConnections.add(4);
icon3.myConnections.add(5);
//and so on
CM.iconsList.add(icon1);
CM.iconsList.add(icon2);
CM.iconsList.add(icon3);
//and so on
}
void Draw(Canvas canvas){
if (canvas!=null)
{
background.draw(canvas);
CM.draw(canvas);
iconEvent.draw(canvas);
}
}
void Update(float dt)
{
CM.Update(dt);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
thread.setRunning(true);
thread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
boolean retry = true;
while (retry)
{
try
{
thread.join();
retry=false;
}
catch (InterruptedException e)
{
}
}
}
}
Background.java
public class Background {
Bitmap BackBitmap;
int x,y;
int ScreenHeight;
Panel root_panel;
public Background(Bitmap bitmap , int Screen_h, Panel _panel) {
this.BackBitmap = bitmap;
this.x=0;
this.y=0;
this.ScreenHeight=Screen_h;
root_panel =_panel;
}
public void draw(Canvas canvas)
{
canvas.drawBitmap(BackBitmap,x,y, null);
}
}
CircleIcon.java
public class CircleIcon {
private Bitmap bitmap;
private int x;
private int y;
CircleManager circManager;
ArrayList<Integer> myConnections;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y=y;
}
public CircleIcon(Bitmap icon, int x, int y) {
bitmap=icon;
this.x=x;
this.y=y;
myConnections = new ArrayList<>();
}
public ArrayList<Integer> getMyConnections() {
return myConnections;
}
public void setMyConnections(ArrayList<Integer> myConnections) {
this.myConnections = myConnections;
}
public void setManager(CircleManager icManager) {
circManager = icManager;
}
public Bitmap getBitmap()
{
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public void draw(Canvas canvas) {
canvas.drawBitmap(bitmap, x, y, null);
}
public void update()
{
// x=+1; example
}
}
CircleManager.java
public class CircleManager {
Bitmap icons;
int screenWidth;
int hour;
int min;
Context myContext;
int ScreenWidht;
public Panel myPanel;
public ArrayList<CircleIcon> iconsList;
public CircleManager(Panel _Panel, Context context,int screenW) {
this.myPanel = _Panel;
this.screenWidth = screenW;
this.myContext = context;
iconsList = new ArrayList<CircleIcon>();
}
public void setScreen(int screenWidth, int screenHeight)
{
this.ScreenWidht=screenWidth;
}
public void draw(Canvas canvas)
{
drawLines(canvas);
for(CircleIcon myIcon: iconsList)
{
myIcon.draw(canvas);
}
}
public void Update(float dt)
{
//some animation updates
}
public void drawLines(Canvas canvas)
{
Paint mPaint = new Paint();
mPaint.setColor(Color.WHITE);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(2);
mPaint.setPathEffect(new DashPathEffect(new float[]{7, 5}, 0));
for (CircleIcon myIcon: iconsList)
{
for( int connectedIcon: myIcon.getMyConnections())
{
Path mPath;
mPath = new Path();
mPath.moveTo(myIcon.getX()+myIcon.getBitmap().getWidth()/2, myIcon.getY()+myIcon.getBitmap().getHeight()/2);
mPath.lineTo(iconsList.get(connectedIcon-1).getX()+myIcon.getBitmap().getWidth()/2, iconsList.get(connectedIcon-1).getY()+myIcon.getBitmap().getHeight()/2);
canvas.drawPath(mPath, mPaint);
}
}
}
public void setManager()
{
for(CircleIcon myIcon: iconsList)
{
myIcon.setManager(this);
}
}
}

Android: Threaded drawing with asynctask

I'm trying to draw fractal on a SurfaceView within asynctask but I'm not sure how to perform it properly. My idea was to create surfaceview (in the main activity) which would contain progress bar, while separate thread would calculate which pixels will be drawn and store this on some kind of "buffer" (I use canvas for this). After that on the surfaceview result should be drawn (which should destroy spinning wheel of progress bar).
I've written this code:
MainActivity.java
public class MainActivity extends Activity {
private Complex constant;
private int bg_color, fg_color;
private static final int nMax = 30, rMax = 2;
private class JuliaThread extends AsyncTask<Complex, Void, Canvas> {
private double re, im, w, h;
private Complex sequence;
private int i;
private Canvas canv;
private Paint p;
private View m;
#Override
protected void onPreExecute() {
super.onPreExecute();
m = (View) findViewById(R.id.sv);
w = m.getWidth();
h = m.getHeight();
canv = new Canvas();
p = new Paint();
}
#Override
protected Canvas doInBackground(Complex... c) {
for (double y=0; y<h; y++) {
for (double x=0; x<w; x++) {
re = (x/w)*3.0-1.5;
im = -(y/h)*3.0-1.5;
sequence = new Complex(re, im);
for (i=1; i<=nMax; i++) {
sequence = sequence.square();
sequence.add(c[0]);
if (sequence.abs() > rMax) break;
}
if (i == nMax) p.setColor(fg_color);
else p.setColor(bg_color);
canv.drawLine((float)x, (float)y, (float)x, (float)y, p);
}
}
return canv;
}
#Override
protected void onPostExecute(Canvas result) {
super.onPostExecute(result);
m.draw(result);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
constant = new Complex(-0.391, -0.587);
bg_color = Color.rgb(0, 0, 0);
fg_color = Color.rgb(255, 255, 255);
new JuliaThread().execute(constant);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="#+id/mainview" >
<SurfaceView
android:id="#+id/sv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</SurfaceView>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/sv"
android:layout_centerHorizontal="true"
android:layout_marginTop="138dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/progressBar1"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="#string/loading"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Unfortunately, this approach doesn't work. Could you explain me, what am I doing wrong and how to do this properly?
You first need to obtain a SurfaceHolder from SurfaceView (by implementing SurfaceHolder.Callback). Then do something like:
final Canvas c = mSurfaceHolder.lockCanvas();
//---draw stuff--
mSurfaceHolder.unlockCanvasAndPost(c);

Categories

Resources