How to add Color Picker in Application? - android

I have developed an Application , which uses screen as a Slate and finger as a Chalk, which is working properly. But I want to use different color types for chalk.
Here is my Code:
MyDemo.java
package com.example.mydemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MyDemo extends Activity {
private LinearLayout root;
private Button btnReset;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_demo);
root = (LinearLayout) findViewById(R.id.root);
btnReset = (Button) findViewById(R.id.reset);
final MyImageView view = new MyImageView(this);
view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
root.addView(view);
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.reset();
}
});
}
}
MyImageView.java
package com.example.mydemo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class MyImageView extends ImageView implements View.OnTouchListener {
private int id = -1;
private Path path;
private List<Path> paths = new ArrayList<Path>();
private List<PointF> points = new ArrayList<PointF>();
boolean multiTouch = false;
public MyImageView(Context context) {
super(context);
this.setOnTouchListener(this);
}
public void reset() {
paths.clear();
points.clear();
path = null;
id = -1;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = createPen(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
for (Path path : paths) {
canvas.drawPath(path, paint);
}
for (int i = 0; i < points.size(); i++) {
PointF p = points.get(i);
canvas.drawText("" + p.x, p.y, i, createPen(Color.WHITE));
}
}
private PointF copy(PointF p) {
PointF copy = new PointF();
copy.set(p);
return copy;
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
multiTouch = false;
id = event.getPointerId(0);
PointF p = getPoint(event, id);
path = new Path();
path.moveTo(p.x, p.y);
paths.add(path);
points.add(copy(p));
break;
case MotionEvent.ACTION_POINTER_DOWN:
multiTouch = true;
for (int i = 0; i < event.getPointerCount(); i++) {
int tId = event.getPointerId(i);
if (tId != id) {
points.add(getPoint(event,i));
}
}
break;
case MotionEvent.ACTION_MOVE:
if (!multiTouch) {
p =getPoint(event, id);
path.lineTo(p.x, p.y);
}
break;
}
invalidate();
return true;
}
private PointF getPoint(MotionEvent event, int i) {
int index = 0;
return new PointF(event.getX(index), event.getY(index));
}
private Paint createPen(int color) {
Paint pen = new Paint();
pen.setColor(color);
float width = 3;
pen.setStrokeWidth(width);
return pen;
}
}
activity_my_demo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/root" xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="#+id/reset" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
/>
</LinearLayout>
Can any one tell me what should be added or changed in my code so that I can use different colors for Chalk?

You can take the sample in your android folder's..
For the color picker go to in this folder:
android/samples/android-YOURS_VERSION/ApiDemos

Use this, review this code. than your problem will be solve
package com.example.changecolor;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity
implements View.OnClickListener, UberColorPickerDialog.OnColorChangedListener {
private int mColor = 0xFFFF0000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Write the version number
PackageManager pm = getPackageManager();
String versionName = "";
try {
PackageInfo pi = pm.getPackageInfo("com.keithwiley.android.ubercolorpickerdemo", 0);
versionName = pi.versionName;
}
catch (Exception e) {
}
TextView textView = (TextView) findViewById(R.id.version);
textView.setText(versionName);
//Initialize the sample
((LinearLayout) findViewById(R.id.LinearLayout)).setBackgroundColor(mColor);
float hsv[] = new float[3];
Color.colorToHSV(mColor, hsv);
if (UberColorPickerDialog.isGray(mColor))
hsv[1] = 0;
if (hsv[2] < .5)
((TextView) findViewById(R.id.sample)).setTextColor(Color.WHITE);
else ((TextView) findViewById(R.id.sample)).setTextColor(Color.BLACK);
//Set up the buttons
Button button = (Button) findViewById(R.id.colorPickerWithTitle);
button.setOnClickListener(this);
button = (Button) findViewById(R.id.colorPickerWithToast);
button.setOnClickListener(this);
}
protected void onPause() {
super.onPause();
}
protected void onResume() {
super.onResume();
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
}
return super.onOptionsItemSelected(item);
}
public void onClick(View v) {
if (v.getId() == R.id.colorPickerWithTitle)
new UberColorPickerDialog(this, this, mColor, true).show();
if (v.getId() == R.id.colorPickerWithToast)
new UberColorPickerDialog(this, this, mColor, false).show();
}
public void colorChanged(int color) {
((LinearLayout) findViewById(R.id.LinearLayout)).setBackgroundColor(mColor=color);
float hsv[] = new float[3];
Color.colorToHSV(mColor, hsv);
//if (UberColorPickerDialog.isGray(mColor))
// hsv[1] = 0;
if (hsv[2] < .5)
((TextView) findViewById(R.id.sample)).setTextColor(Color.WHITE);
else ((TextView) findViewById(R.id.sample)).setTextColor(Color.BLACK);
}
}
And use the color picker class

Related

changing image with imageswitcher and onTouch

I want to make android app like the following site.
https://sectional-anatomy.org/ct-abdomen/ or like https://radiopaedia.org/cases/squamous-cell-carcinoma-oral-cavity
There are multiple pictures and these are changing by scrolling.
I have done something like that with imageswitcher and onTouch event with action_down and action_up but it doesn't work because when I remove my finger then it goes to the first image it doesn't stay where I left.
Here is my code:
package com.radiology.radiologymenu.tomografi;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.radiology.radiologymenu.R;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class ImageChangeActivity extends AppCompatActivity {
private ImageSwitcher imageSwitcher;
private ImageView box;
// Size
private int frameHeight;
private int boxSize;
private int screenHeight;
// Position
private int boxY;
// Speed
private int boxSpeed;
// Score
private int score = 0;
// Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
// Status Check
private boolean action_flg = false;
private boolean start_flg = false;
private String pic;
private ArrayList<Integer> slidePictures;
private static final Integer[] image= {
R.drawable.sagittal_boyun_1, R.drawable.sagittal_boyun_2, R.drawable.sagittal_boyun_3, R.drawable.sagittal_boyun_4,
R.drawable.sagittal_boyun_5, R.drawable.sagittal_boyun_6, R.drawable.sagittal_boyun_7, R.drawable.sagittal_boyun_8,
R.drawable.sagittal_boyun_9, R.drawable.sagittal_boyun_10, R.drawable.sagittal_boyun_11,
R.drawable.sagittal_boyun_12, R.drawable.sagittal_boyun_13, R.drawable.sagittal_boyun_14, R.drawable.sagittal_boyun_15,
R.drawable.sagittal_boyun_16, R.drawable.sagittal_boyun_17, R.drawable.sagittal_boyun_18, R.drawable.sagittal_boyun_19,
R.drawable.sagittal_boyun_20, R.drawable.sagittal_boyun_21, R.drawable.sagittal_boyun_22, R.drawable.sagittal_boyun_23,
R.drawable.sagittal_boyun_24, R.drawable.sagittal_boyun_25, R.drawable.sagittal_boyun_26, R.drawable.sagittal_boyun_27,
R.drawable.sagittal_boyun_28, R.drawable.sagittal_boyun_29, R.drawable.sagittal_boyun_30, R.drawable.sagittal_boyun_31,
R.drawable.sagittal_boyun_32, R.drawable.sagittal_boyun_33, R.drawable.sagittal_boyun_34, R.drawable.sagittal_boyun_35,
R.drawable.sagittal_boyun_36, R.drawable.sagittal_boyun_37, R.drawable.sagittal_boyun_38, R.drawable.sagittal_boyun_39,
R.drawable.sagittal_boyun_40, R.drawable.sagittal_boyun_41, R.drawable.sagittal_boyun_42, R.drawable.sagittal_boyun_43,
R.drawable.sagittal_boyun_44, R.drawable.sagittal_boyun_45 };
int i = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_activity_main);
pic = getIntent().getExtras().getString("pic");
slidePictures = (ArrayList<Integer>) getIntent().getExtras().getSerializable("slidePictures");
getView2(pic,slidePictures);
}
public void getView2(String strings, ArrayList<Integer> slidePictures){
setContentView(R.layout.slide_activity_main);
TextView textView = (TextView) findViewById(R.id.resimText);
textView.setText(strings.toString());
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
box = (ImageView) findViewById(R.id.box);
// Get screen size.
WindowManager wm = getWindowManager();
Display disp = wm.getDefaultDisplay();
Point size = new Point();
disp.getSize(size);
screenHeight = size.y;
boxSpeed = Math.round(screenHeight / 60); // 1280 / 60 = 21.333... => 21
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
FrameLayout.LayoutParams params = new ImageSwitcher.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(params);
return imageView;
}
});
imageSwitcher.setImageResource(slidePictures.get(0));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
public void changePos() {
// Move Box
if (action_flg == true) {
// Touching
boxY -= boxSpeed;
if (i<slidePictures.size()-1){
i++;
imageSwitcher.setImageResource(slidePictures.get(i));
}
} else {
// Releasing
boxY += boxSpeed;
if (i>0){
i--;
imageSwitcher.setImageResource(slidePictures.get(i));
}
}
// Check box position.
if (boxY < 0) boxY = 0;
if (boxY > frameHeight - boxSize) boxY = frameHeight - boxSize;
box.setY(boxY);
}
public boolean onTouchEvent(MotionEvent me) {
if (start_flg == false) {
start_flg = true;
// Why get frame height and box height here?
// Because the UI has not been set on the screen in OnCreate()!!
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
frameHeight = frame.getHeight();
boxY = (int)box.getY();
// The box is a square.(height and width are the same.)
boxSize = box.getHeight();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
changePos();
}
});
}
}, 0, 40);
} else {
if (me.getAction() == MotionEvent.ACTION_DOWN) {
action_flg = false;
} else if (me.getAction() == MotionEvent.ACTION_UP) {
action_flg = true;
}
}
return true;
}
}

AnimationDrawable into framelayout beside SurfaceView- Android

Hello all,
in my app, can i make an character (like, cartoon character...) to animate when i touch the screen?
i have another bitmaps (static not animated) on the screen.
i have all this character (10) bitmaps in all animation position (like a cartoon)
this is the code.. ( I NEED TO ANIMATE IT FOR EACH TOUCH )
`
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
public class Show extends Activity
{
private Bitmap imageOne;
private Bitmap imageTwo;
private Bitmap imageThree;
private List<Bitmap> images;
private ExplainView myView;
private AnimationDrawable animation;
private ImageView image;`
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(0x00000400, 0x00000400);
setContentView(R.layout.frame_layout);
image = new ImageView(this);
image.setBackgroundResource(R.drawable.tom_anim);
animation = (AnimationDrawable) rocketImage.getBackground();
images = new ArrayList<Bitmap>();
praper();
myView = new ExplainView(this,images,1); <------ this is the surface view class
FrameLayout fl = (FrameLayout)findViewById(R.id.frameLayout);
fl.addView(myView);
fl.addView(image);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
new Runnable() {
#Override
public void run() {
image.setVisibility(View.VISIBLE);
animation.stop();
animation.start();
}
};
}
return true;
}
private void praper()
{
imageOne = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_1);
imageTwo = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_2);
imageThree = BitmapFactory.decodeResource(getResources(), R.drawable.trans_ar_alpha_3);
images.add(0,imageOne);
images.add(1, imageTwo);
images.add(2, imageThree);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus)
{
animation.start();
}
else
{
animation.stop();
}
}
}`
of course you can simply by using
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
x = arg1.getX();
y = arg1.getY();
switch(arg1.getAction())
{
case MotionEvent.ACTION_DOWN:
sx=arg1.getX();
sy = arg1.getY();
break;
case MotionEvent.ACTION_UP:
fx=arg1.getX();
fy = arg1.getY();
break;
}

Couldn't click on buttons when child view is added?

When I use child view then the buttons which are in the root view are disabled. I could not click on them.
I am trying to develop application in which input is made by connecting buttons with lines. If user wants to enter
some thing then he have to touch buttons by connecting them with lines. It is very similar to android pattern
unlock. But in our application in place of dots of grid, numbers will be shown.
activity_demo_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rty"
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=".DemoMainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="222.08203dp"
android:layout_marginTop="270.53426dp"
android:text="1" />
<Button
android:id="#+id/button2"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="162.08203dp"
android:layout_marginTop="314.12678dp"
android:text="2" />
<Button
android:id="#+id/button3"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="87.917960dp"
android:layout_marginTop="314.12678dp"
android:text="3" />
<Button
android:id="#+id/button4"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="27.917960dp"
android:layout_marginTop="270.53423dp"
android:text="4" />
</RelativeLayout>
DemoMainActivity.java :
package com.example.demo;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
public class DemoMainActivity extends Activity {
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_main);
rl = (RelativeLayout)findViewById(R.id.rty);
Button b1=(Button)findViewById(R.id.button2);
final NewPattern b = new NewPattern(this);
b1.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View arg0) {
try{
rl.getRootView();
rl.addView(b);
}
catch(Exception ex){}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.demo_main, menu);
return true;
}
}
NewPattern.java:
package com.example.demo;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
//import com.example.newpattern.PatternMainActivity;
import android.widget.RelativeLayout;
public class NewPattern extends View
{
private Paint m_paint;
private static Bitmap m_bitmap;
private Canvas m_canvas;
private Path m_path;
private Paint m_bitmapPaint;
private DisplayMetrics m_metrics;
private int m_color = 0xFFFF0000;
static boolean m_pathDrawn = false;
private float m_X, m_Y;
private static final float TOUCH_TOLERANCE = 4;
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.rty);
#SuppressLint("NewApi")
private void touchman(float g, float h){
final float btn1x = b1.getX();
//float btn2x= b1.getY();
if(g==btn1x){
rl.getRootView();
}
}
public NewPattern(Context context, AttributeSet attrs) {
super(context, attrs);
//Your code
// btn1.setText("fdsf");
}
public NewPattern(Context p_c)
{
super(p_c);
try{
m_paint = new Paint();
m_paint.setAntiAlias(true);
m_paint.setDither(true);
m_paint.setColor(m_color);
/*new ColorPickerDialog(p_c, new OnColorChangedListener()
{
public void colorChanged(int p_color)
{
m_paint.setColor(p_color);
m_color = p_color;
}
}, 0xFFFF0000).show();*/
m_paint.setStyle(Paint.Style.STROKE);
m_paint.setStrokeJoin(Paint.Join.ROUND);
m_paint.setStrokeCap(Paint.Cap.ROUND);
m_paint.setStrokeWidth(12);
m_metrics = p_c.getResources().getDisplayMetrics();
m_bitmap =
Bitmap.createBitmap(m_metrics.widthPixels, m_metrics.heightPixels,
Bitmap.Config.ARGB_8888);
m_canvas = new Canvas(m_bitmap);
m_path = new Path();
m_bitmapPaint = new Paint(Paint.DITHER_FLAG);
}
catch(Exception ex){}}
public void onerase()
{
m_canvas = null;
}
#Override
protected void onSizeChanged(int p_w, int p_h, int p_oldw, int p_oldh)
{
super.onSizeChanged(p_w, p_h, p_oldw, p_oldh);
}
#Override
protected void onDraw(Canvas p_canvas)
{try{
p_canvas.drawColor(0x00000000);
p_canvas.drawBitmap(m_bitmap, 0, 0, m_bitmapPaint);
p_canvas.drawPath(m_path, m_paint);}
catch(Exception ex){}
}
#SuppressLint("NewApi")
private void touch_start(float p_x, float p_y)
{//try{
m_path.reset();
m_path.moveTo(p_x, p_y);
m_X = p_x;
m_Y = p_y;
//}
//catch(Exception ex){}
}
private void touch_move(float p_x, float p_y)
{try{
float m_dx = Math.abs(p_x - m_X);
float m_dy = Math.abs(p_y - m_Y);
if (m_dx >= TOUCH_TOLERANCE || m_dy >= TOUCH_TOLERANCE)
{
m_path.quadTo(m_X, m_Y, (p_x + m_X) / 2, (p_y + m_Y) / 2);
m_X = p_x;
m_Y = p_y;
m_pathDrawn = true;
}}
catch(Exception ex){}
}
private void touch_up()
{try{
m_path.lineTo(m_X, m_Y);
// commit the path to our offscreen
m_canvas.drawPath(m_path, m_paint);
// kill this so we don't double draw
m_path.reset();
}
catch(Exception ex){}
}
#SuppressLint("NewApi")
#Override
public boolean onTouchEvent(MotionEvent p_event)
{try{
float m_x = p_event.getX();
float m_y = p_event.getY();
switch (p_event.getAction())
{
case MotionEvent.ACTION_DOWN:
touch_start(m_x, m_y);
//touchman(m_x, m_y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(m_x, m_y);
// touchman(m_x, m_y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
//touchman(m_x, m_y);
invalidate();
break;
}
return true;
}
catch(Exception ex){}
return true;
}}

Adding drawable image to background of canvas

I know its possible to paint the background of canvas using
mPaint = new Paint();
mPaint.setColor(Color.RED);
Im just wondering how to i set a permanent background for it. Ive tried using the xml file but nothing happens. Any ideas?
This is the source code of the project, ive been following a tutorial how to do it because im fairly unfamiliar with bitmaps.
Canvas Class
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class GameBoard extends View{
private int mFlagX = -1;
private int mFlagY = -1;
private Bitmap mBitmap = null;
private Bitmap nBitmap = null;
private Paint mPaint = null;
private boolean isFlagHidden = false;
private int mBoundX = -1;
private int mBoundY = -1;
//play with these values to make the app more or less challenging
public final int CLOSER = 50;
public final int CLOSE = 100;
public GameBoard(Context context, AttributeSet aSet) {
super(context, aSet);
//load our bitmap
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.star);
//create a paint brush
mPaint = new Paint();
mPaint.setColor(Color.RED);
}
#Override
public void onDraw(Canvas canvas) {
//initialize
if ((mFlagX < 1) || (mFlagY < 1)) {
mFlagX = (int) (getWidth() / 2) - mBitmap.getWidth() / 2;
mFlagY = (int) (getHeight() / 2) - mBitmap.getHeight() / 2;
mBoundX = (int)getWidth() - mBitmap.getWidth();
mBoundY = (int)getHeight() - mBitmap.getHeight();
}
//draw background
canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
//draw the flag
if (!isFlagHidden) {
canvas.drawBitmap(mBitmap, mFlagX, mFlagY, null);
}
}
public void hideTheFlag(){
//randomize flag location
mFlagX = (int) Math.ceil(Math.random() * mBoundX);
mFlagY = (int) Math.ceil(Math.random() * mBoundY);
isFlagHidden = true;
//force redraw
invalidate();
}
public void giveUp(){
isFlagHidden = false;
//force redraw
invalidate();
}
public Indicators takeAGuess(float x, float y) {
//this is our "warm" area
Rect prettyClose = new Rect(mFlagX - CLOSE, mFlagY - CLOSE, mFlagX+mBitmap.getWidth() + CLOSE, mFlagY+mBitmap.getHeight() + CLOSE);
//normalize
if (prettyClose.left < 0) prettyClose.left = 0;
if (prettyClose.top < 0) prettyClose.top = 0;
if (prettyClose.right > mBoundX) prettyClose.right = mBoundX;
if (prettyClose.bottom > mBoundY) prettyClose.bottom = mBoundY;
//this is our "hot" area
Rect reallyClose = new Rect(mFlagX - CLOSER, mFlagY - CLOSER, mFlagX+mBitmap.getWidth() + CLOSER, mFlagY+mBitmap.getHeight() + CLOSER);
//normalize
if (reallyClose.left < 0) reallyClose.left = 0;
if (reallyClose.top < 0) reallyClose.top = 0;
if (reallyClose.right > mBoundX) reallyClose.right = mBoundX;
if (reallyClose.bottom > mBoundY) reallyClose.bottom = mBoundY;
//this is the area that contains our flag
Rect bullsEye = new Rect(mFlagX, mFlagY, mFlagX+mBitmap.getWidth(), mFlagY+mBitmap.getHeight());
//check to see where on the board the user pressed
if (bullsEye.contains((int) x, (int)y)) {
//found it
isFlagHidden = false;
invalidate();
return Indicators.BULLSEYE;
} else if (reallyClose.contains((int) x, (int)y)) {
//hot
return Indicators.HOT;
} else if (prettyClose.contains((int)x, (int)y)) {
//warm
return Indicators.WARM;
} else {
//not even close
return Indicators.COLD;
}
}
}
Game Class
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class FindTheStar extends Activity implements OnTouchListener, OnClickListener{
private GameBoard mGameBoard = null;
private boolean isFlagHidden = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_star);
mGameBoard = (GameBoard) findViewById(R.id.Hide_canvas);
mGameBoard.setOnTouchListener(this);
Button b = (Button) findViewById(R.id.the_button);
b.setOnClickListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.Hide_canvas) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (isFlagHidden) {
TextView tv = (TextView)findViewById (R.id.the_label);
switch (mGameBoard.takeAGuess(event.getX(), event.getY())) {
case BULLSEYE:
Button b = (Button) findViewById(R.id.the_button);
isFlagHidden = false;
b.setText("Go Hide!");
tv.setText("You found me!");
tv.setTextColor(Color.GREEN);
break;
case HOT:
tv.setText("You're hot!");
tv.setTextColor(Color.RED);
break;
case WARM:
tv.setText("Getting warm...");
tv.setTextColor(Color.YELLOW);
break;
case COLD:
tv.setText("You're cold.");
tv.setTextColor(Color.BLUE);
break;
}
}
}
return true;
}
return false;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.the_button) {
TextView tv = (TextView)findViewById (R.id.the_label);
tv.setText("");
Button b = (Button) findViewById(R.id.the_button);
isFlagHidden = !isFlagHidden;
if (isFlagHidden) {
b.setText("Can't find me?");
mGameBoard.hideTheFlag();
} else {
b.setText("Go Hide!");
mGameBoard.giveUp();
}
}
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/the_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20sp"
android:layout_marginBottom="10dip"
android:text="Lets Play Hide and Seek!"/>
<Button
android:id="#+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginBottom="10dip"
android:text="Go Hide!"/>
<app.autismapp.GameBoard
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/Hide_canvas"/>
</LinearLayout>
yes you can set your permanent background using xml layout..i done this by creating two class.
this is my code in MainACtivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final BrushView view=new BrushView(this);
setContentView(R.layout.mylayout);//removed this one if the paint doesnt work
view.setBackgroundResource(R.drawable.background);//to set background
setContentView(view);// to display the background
and my second class
public class PaintView extends View {
private Paint paint = new Paint();
public LayoutParams params;
public PaintView(Context context) {
super(context);
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
i hope it gives you an idea

How to save bitmap for undo functionality in paint in Android?

I am making an application in which i can implement undo functionality so i get previous drawing lines ..but i am unable to do it. can anybody help give some example for i will be gratefully appreciate.
Thanks
make an stack(take ArrayList) of the points and based on action move position.
refer concept http://www.tutorialforandroid.com/2010/11/drawing-with-canvas-in-android-undoredo.html
perfect Android add undo feature to finger paint example in api demo
Include this code in that u can Undro,Redo and can change color while drawing too...
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import com.almondmendoza.R;
import com.almondmendoza.drawings.brush.Brush;
import com.almondmendoza.drawings.brush.CircleBrush;
import com.almondmendoza.drawings.brush.PenBrush;
import java.io.File;
import java.io.FileOutputStream;
public class DrawingActivity extends Activity implements View.OnTouchListener{
private DrawingSurface drawingSurface;
private DrawingPath currentDrawingPath;
private Paint currentPaint;
private Button redoBtn;
private Button undoBtn;
private Brush currentBrush;
private File APP_FILE_PATH = new File("/sdcard/TutorialForAndroidDrawings");
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawing_activity);
setCurrentPaint();
currentBrush = new PenBrush();
drawingSurface = (DrawingSurface) findViewById(R.id.drawingSurface);
drawingSurface.setOnTouchListener(this);
redoBtn = (Button) findViewById(R.id.redoBtn);
undoBtn = (Button) findViewById(R.id.undoBtn);
redoBtn.setEnabled(false);
undoBtn.setEnabled(false);
}
private void setCurrentPaint(){
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFFFFFF00);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
}
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
currentDrawingPath = new DrawingPath();
currentDrawingPath.paint = currentPaint;
currentDrawingPath.path = new Path();
currentBrush.mouseDown(currentDrawingPath.path, motionEvent.getX(), motionEvent.getY());
}else if(motionEvent.getAction() == MotionEvent.ACTION_MOVE){
currentBrush.mouseMove( currentDrawingPath.path, motionEvent.getX(), motionEvent.getY() );
}else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
currentBrush.mouseUp( currentDrawingPath.path, motionEvent.getX(), motionEvent.getY() );
drawingSurface.addDrawingPath(currentDrawingPath);
drawingSurface.isDrawing = true;
undoBtn.setEnabled(true);
redoBtn.setEnabled(false);
}
return true;
}
public void onClick(View view){
switch (view.getId()){
case R.id.colorRedBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFFFF0000);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.colorBlueBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFF00FF00);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.colorGreenBtn:
currentPaint = new Paint();
currentPaint.setDither(true);
currentPaint.setColor(0xFF0000FF);
currentPaint.setStyle(Paint.Style.STROKE);
currentPaint.setStrokeJoin(Paint.Join.ROUND);
currentPaint.setStrokeCap(Paint.Cap.ROUND);
currentPaint.setStrokeWidth(3);
break;
case R.id.undoBtn:
drawingSurface.undo();
if( drawingSurface.hasMoreUndo() == false ){
undoBtn.setEnabled( false );
}
redoBtn.setEnabled( true );
break;
case R.id.redoBtn:
drawingSurface.redo();
if( drawingSurface.hasMoreRedo() == false ){
redoBtn.setEnabled( false );
}
undoBtn.setEnabled( true );
break;
case R.id.saveBtn:
final Activity currentActivity = this;
Handler saveHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
final AlertDialog alertDialog = new AlertDialog.Builder(currentActivity).create();
alertDialog.setTitle("Saved 1");
alertDialog.setMessage("Your drawing had been saved :)");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
} ;
new ExportBitmapToFile(this,saveHandler, drawingSurface.getBitmap()).execute();
break;
case R.id.circleBtn:
currentBrush = new CircleBrush();
break;
case R.id.pathBtn:
currentBrush = new PenBrush();
break;
}
}
private class ExportBitmapToFile extends AsyncTask<Intent,Void,Boolean> {
private Context mContext;
private Handler mHandler;
private Bitmap nBitmap;
public ExportBitmapToFile(Context context,Handler handler,Bitmap bitmap) {
mContext = context;
nBitmap = bitmap;
mHandler = handler;
}
#Override
protected Boolean doInBackground(Intent... arg0) {
try {
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
final FileOutputStream out = new FileOutputStream(new File(APP_FILE_PATH + "/myAwesomeDrawing.png"));
nBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
return true;
}catch (Exception e) {
e.printStackTrace();
}
//mHandler.post(completeRunnable);
return false;
}
#Override
protected void onPostExecute(Boolean bool) {
super.onPostExecute(bool);
if ( bool ){
mHandler.sendEmptyMessage(1);
}
}
}
}

Categories

Resources