Android:How to add a button in surface view - android

I'm drawing some graphics and i would like to add a couple of buttons to it. But with the surface view how do we add these buttons programatically ?

Enclose your surfaceView with a FrameLayout in your xml Layout. Then add your buttons to the same FrameLayout. Make sure they are placed below the surface view so they get drawn on top of it. (Might be a good idea to bundle them in another Layout and add that to the FrameLayout.)
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView android:id="#+id/surfaceView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></SurfaceView>
<LinearLayout android:id="#+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content">
<Button android:text="Button" android:id="#+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Button" android:id="#+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
</FrameLayout>

Thank you so much Androidica..
Your xml has helped me to figure out the following solution programatically without using any xml..
public class LudoActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
FrameLayout game = new FrameLayout(this);
GameView gameView = new GameView (this);
LinearLayout gameWidgets = new LinearLayout (this);
Button endGameButton = new Button(this);
TextView myText = new TextView(this);
endGameButton.setWidth(300);
endGameButton.setText("Start Game");
myText.setText("rIZ..i");
gameWidgets.addView(myText);
gameWidgets.addView(endGameButton);
game.addView(gameView);
game.addView(gameWidgets);
setContentView(game);
endGameButton.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = new Intent(this, LudoActivity.class);
startActivity(intent);
// re-starts this activity from game-view. add this.finish(); to remove from stack
}
}
while GameView is;
public class GameView extends SurfaceView {
public GameView(Context context) {
super(context);
/*
* your code
*/
}
}

Make your own button:
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
public class GButton
{
public Matrix btn_matrix = new Matrix();
public RectF btn_rect;
float width;
float height;
Bitmap bg;
public GButton(float width, float height, Bitmap bg)
{
this.width = width;
this.height = height;
this.bg = bg;
btn_rect = new RectF(0, 0, width, height);
}
public void setPosition(float x, float y)
{
btn_matrix.setTranslate(x, y);
btn_matrix.mapRect(btn_rect);
}
public void draw(Canvas canvas)
{
canvas.drawBitmap(bg, btn_matrix, null);
}
}
on touch event:
float x = ev.getX();
float y = ev.getY();
if (my_button.btn_rect.contains(x, y))
{
// handle on touch here
}
alternatively, even better, if you want to also rotate the button it will not be axis-aligned, then use the invert matrix, instead of mapRect map the touch points x,y:
float pts[] = {x, y};
my_button.invert_matrix.mapPoints(pts);
if (my_button.btn_rect.contains(pts[0], pts[1])
{
// handle on touch here
}

We can use frame layout for surface view drawing very easily .
like this
<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:orientation="vertical">
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="fill_parent"
android:layout_height="430dp"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:gravity="center_horizontal"
android:layout_gravity="bottom"
android:background="#c2300f">
<Button
android:id="#+id/buttonColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color" />
</LinearLayout>
</LinearLayout>
And Main activity is
package com.example.surfacetuto;
import android.app.Activity;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
DrawingSurface ds;
FrameLayout frm;
Button btnC;
int color=0xfff00000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ds=new DrawingSurface(this);
setContentView(R.layout.activity_main);
frm=(FrameLayout)findViewById(R.id.frameLayout);
frm.addView(ds);
btnC=(Button)findViewById(R.id.buttonColor);
btnC.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.buttonColor:
Toast.makeText(getApplicationContext(), "Color", 2).show();
ds.colorNew();
break;
default:
break;
}
}
}
And Drawing Surface class is
package com.example.surfacetuto;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class DrawingSurface extends SurfaceView implements SurfaceHolder.Callback {
Canvas cacheCanvas;
Bitmap backBuffer;
int width, height, clientHeight;
Paint paint;
Context context;
SurfaceHolder mHolder;
public DrawingSurface(Context context) {
super(context);
this.context = context;
init();
}
public DrawingSurface(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
private void init() {
mHolder = getHolder();
mHolder.addCallback(this);
}
int lastX, lastY, currX, currY;
boolean isDeleting;
#Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
int action = event.getAction();
switch(action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getX();
lastY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
if(isDeleting) break;
currX = (int) event.getX();
currY = (int) event.getY();
cacheCanvas.drawLine(lastX, lastY, currX, currY, paint);
lastX = currX;
lastY = currY;
break;
case MotionEvent.ACTION_UP:
if(isDeleting) isDeleting = false;
break;
case MotionEvent.ACTION_POINTER_DOWN:
cacheCanvas.drawColor(Color.WHITE);
isDeleting = true;
break;
case MotionEvent.ACTION_POINTER_UP:
break;
}
draw();
return true;
}
protected void draw() {
if(clientHeight==0) {
clientHeight = getClientHeight();
height = clientHeight;
backBuffer = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888);
cacheCanvas.setBitmap(backBuffer);
cacheCanvas.drawColor(Color.WHITE);
}
Canvas canvas = null;
try{
canvas = mHolder.lockCanvas(null);
canvas.drawBitmap(backBuffer, 0,0, paint);
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(mHolder!=null) mHolder.unlockCanvasAndPost(canvas);
}
}
private int getClientHeight() {
Rect rect= new Rect();
Window window = ((Activity)context).getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight= rect.top;
int contentViewTop= window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight= contentViewTop - statusBarHeight;
return ((Activity)context).getWindowManager().getDefaultDisplay().
getHeight() - statusBarHeight - titleBarHeight;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
width = getWidth();
height = getHeight();
cacheCanvas = new Canvas();
backBuffer = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888);
cacheCanvas.setBitmap(backBuffer);
cacheCanvas.drawColor(Color.WHITE);
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeJoin(Paint.Join.ROUND);
draw();
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
public void colorNew() {
// TODO Auto-generated method stub
paint.setColor(Color.GRAY);
}
}

Related

my image not set in the center of relative layout and its not showing complete image using flood-fill and canvas

I want to set my bitmap converted image in relative layout with the help of custom view but my image not set in the center of relative layout and its not showing complete image
My relative layout where I set my bitmap image`package org.boostram.justcolor;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.flask.colorpicker.ColorPickerView;
import com.flask.colorpicker.OnColorChangedListener;
import com.flask.colorpicker.OnColorSelectedListener;
import org.boostram.justcolor.Utils.util;
import static android.R.attr.src;
public class FillPaintActivity extends Activity implements View.OnTouchListener {
private RelativeLayout dashBoard;
Paint paint;
private MyView myView;
int a = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = new MyView(this);
setContentView(R.layout.activity_fill_paint);
ColorPickerView colorPickerView = (ColorPickerView) findViewById(R.id.color_picker_view);
// colorPickerView.setColor(Color.WHITE,true);
paint.setColor(Color.WHITE);
colorPickerView.setInitialColor(Color.WHITE, true);
colorPickerView.addOnColorChangedListener(new OnColorChangedListener() {
#Override
public void onColorChanged(int selectedColor) {
a = 1;
paint.setColor(selectedColor);
// Handle on color change
// Log.d("ColorPicker", "onColorChanged: 0x" + Integer.toHexString(selectedColor));
}
});
colorPickerView.addOnColorSelectedListener(new OnColorSelectedListener() {
#Override
public void onColorSelected(int selectedColor) {
paint.setColor(selectedColor);
// myView.changePaintColor(selectedColor);
Toast.makeText(FillPaintActivity.this, "selectedColor: " +
Integer.toHexString(selectedColor).toUpperCase(),
// Toast.LENGTH_SHORT).show();
}
});
dashBoard = (RelativeLayout) findViewById(R.id.dashBoard);
dashBoard.addView(myView);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
public class MyView extends View {
// private Paint paint;
private Path path;
public Bitmap mBitmap;
public ProgressDialog pd;
final Point p1 = new Point();
public Canvas canvas;
public MyView(Context context) {
super(context);
paint = new Paint();
paint.setAntiAlias(true);
pd = new ProgressDialog(context);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
// paint.setStrokeWidth(5f);
// BitmapDrawable drawable = (BitmapDrawable)
context.getDrawable(R.drawable.unnamed);
// Bitmap bmp = drawable.getBitmap();
// Bitmap mBitmap = Bitmap.createScaledBitmap(bmp, 120, 120,
false);
mBitmap = BitmapFactory.decodeResource(getResources(),
util.Id).copy(Bitmap.Config.ARGB_8888, true);
//mBitmap =
Bitmap.createScaledBitmap((BitmapFactory.decodeResource(getResources(),
util.Id).copy(Bitmap.Config.ARGB_8888, true)),1500,1380,false);
this.path = new Path();
}
#Override
protected void onDraw(Canvas canvas) {
this.canvas = canvas;
// Display display = getWindowManager().getDefaultDisplay();
// int displayWidth = display.getWidth();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(getResources(), util.Id, options);
// int width = options.outWidth;
// if (width > displayWidth)
// {
// int widthRatio = Math.round((float) width / (float)
displayWidth);
// options.inSampleSize = widthRatio;
// }
// options.inJustDecodeBounds = false;
// Bitmap scaledBitmap =
BitmapFactory.decodeResource(getResources(),util.Id , options);
canvas.drawBitmap(mBitmap,0,0 ,paint);
// mBitmap = BitmapFactory.decodeResource
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (a == 0) {
Toast.makeText(FillPaintActivity.this, "Select Any Color First",
Toast.LENGTH_SHORT).show();
}
// Toast.makeText(FillPaintActivity.this, myView.getWidth()+""+myView.getHeight(), Toast.LENGTH_LONG).show();
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
p1.x = (int) x;
p1.y = (int) y;
if (p1.x < mBitmap.getWidth() && p1.y < mBitmap.getHeight()) {
final int sourceColor = mBitmap.getPixel((int) x, (int) y);
final int targetColor = paint.getColor();
new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
invalidate();
}
// else {
// Toast.makeText(FillPaintActivity.this, "You touched outside the Image", Toast.LENGTH_SHORT).show();
// }
}
return true;
}
public void clear() {
path.reset();
invalidate();
}
public void changePaintColor(int color) {
paint.setColor(color);
}
class TheTask extends AsyncTask<Void, Integer, Void> {
Bitmap bmp;
Point pt;
int replacementColor, targetColor;
public TheTask(Bitmap bm, Point p, int sc, int tc) {
this.bmp = bm;
this.pt = p;
this.replacementColor = tc;
this.targetColor = sc;
}
#Override
protected void onPreExecute() {
// pd.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
FloodFill floodFill = new FloodFill(bmp, targetColor, replacementColor);
floodFill.floodFill(pt.x, pt.y);
return null;
}
#Override
protected void onPostExecute(Void result) {
invalidate();
}
}
}
}
https://i.stack.imgur.com/AHpcb.png
My bitmap converted image not set in center of relative layout through view. Kindly help me i'm stuck here for almost two week. Help

How to scale custom image views in android?

In my face detector project, I'm using a custom ImageView (MyView) to detect faces and draw rectangles on the detected faces. For this I have set fixed dimensions for my customview (MyView) and trying to scale the bitmap to fit the customview. But somehow I'm not able to achieve this.
I have gone throught all similar questions on SO. Please help.
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"
tools:context=".MainActivity">
<com.sample.facedetector.MyView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="#+id/MyViewId"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:scaleType="centerCrop"/>
MainActivity
package com.sample.facedetector;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyView faceDetectorView = (MyView) findViewById(R.id.MyViewId);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.face_detector).copy(Bitmap.Config.RGB_565,true);
faceDetectorView.setImage(bmp);
faceDetectorView.setScaleType(ImageView.ScaleType.CENTER_CROP);
faceDetectorView.detectFaces();
}
MyView
package com.sample.facedetector;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import android.widget.ImageView;
public class MyView extends ImageView {
private Bitmap mFaceBitmap;
private int count = 0;
private FaceDetector.Face[] faces;
private Bitmap image;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void detectFaces(){
FaceDetector myFaceDetector = null;
mFaceBitmap = image.copy(Bitmap.Config.RGB_565, true);
int targetWidth = mFaceBitmap.getWidth();
int targetHeight = mFaceBitmap.getHeight();
faces= new FaceDetector.Face[5];
int[] fpx =null;
int[] fpy = null;
myFaceDetector = new FaceDetector(targetWidth,targetHeight,5);
count = myFaceDetector.findFaces(mFaceBitmap, faces);
setWillNotCacheDrawing(true);
requestLayout();
this.invalidate();
}
/*#Override
public void setScaleType(ScaleType scaleType) {
super.setScaleType(ScaleType.CENTER);
invalidate();
}*/
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mFaceBitmap,0,0,null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
if (count > 0) {
for (int i = 0; i < count; i++) {
FaceDetector.Face face = faces[i];
PointF midPoint = new PointF();
face.getMidPoint(midPoint);
float eyeDistance = face.eyesDistance();
canvas.drawRect(midPoint.x-eyeDistance, midPoint.y-eyeDistance, midPoint.x+eyeDistance, midPoint.y+eyeDistance, myPaint);
}
}
}
#Override
public void setImageResource(#DrawableRes int resId) {
super.setImageResource(resId);
invalidate();
}
public void setImage(Bitmap image) {
this.image = image;
}
}

Android triangle custom buttons

I want to make 2 diagonal triangle buttons like in this question.
How can I achieve this? Should I make a drawable xml with a rectangle and rotate it somehow? Should I make an image and make it clickable only on the triangle parts with the help of mathematics?
package com.example.buttonsView;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.FillType;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Region;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class TwoButtons extends View {
private Path path;
private Path path1;
private Region region;
private Region region1;
private static int GAP=10;
private ButtonClickEvents buttonClickEvent;
public interface ButtonClickEvents{
public void redButtonClick();
public void blueButtonClick();
}
public void setOnButtonClickEvent(ButtonClickEvents buttonClickEvent) {
this.buttonClickEvent=buttonClickEvent;
}
public TwoButtons(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(Color.GRAY);
Paint paint = new Paint();
paint.setColor(android.graphics.Color.BLACK);
canvas.drawPaint(paint);
paint.setStrokeWidth(0);
paint.setColor(android.graphics.Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
Point a = new Point(GAP, GAP);
Point b = new Point(GAP, getHeight()-2*GAP);
Point c = new Point(getWidth()-2*GAP, GAP);
path = new Path();
path.setFillType(FillType.EVEN_ODD);
path.moveTo(a.x, a.y);
path.lineTo(b.x, b.y);
path.lineTo(c.x, c.y);
path.close();
canvas.drawPath(path, paint);
RectF rectF = new RectF();
path.computeBounds(rectF, true);
region = new Region();
region.setPath(path, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom));
paint.setColor(Color.BLUE);
Point a1 = new Point(getWidth()-GAP, getHeight()-GAP);
Point b1 = new Point(getWidth()-GAP, 2*GAP);
Point c1 = new Point(2*GAP, getHeight()-GAP);
path1 = new Path();
path1.setFillType(FillType.EVEN_ODD);
path1.moveTo(a1.x, a1.y);
path1.lineTo(b1.x, b1.y);
path1.lineTo(c1.x, c1.y);
path1.close();
canvas.drawPath(path1, paint);
RectF rectF1 = new RectF();
path1.computeBounds(rectF1, true);
region1 = new Region();
region1.setPath(path1, new Region((int) rectF1.left, (int) rectF1.top, (int) rectF1.right, (int) rectF1.bottom));
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Point point = new Point();
point.x = (int) event.getX();
point.y = (int) event.getY();
invalidate();
if(region.contains((int)point.x,(int) point.y))
{
if(buttonClickEvent!=null)
buttonClickEvent.redButtonClick();
}else if(region1.contains((int)point.x,(int) point.y))
{
if(buttonClickEvent!=null)
buttonClickEvent.blueButtonClick();
}
return true;
}
return false;
}
}
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="com.example.buttonsView.MainActivity" >
<com.example.buttonsView.TwoButtons
android:id="#+id/twoButtons1"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
MainActivity.java
package com.example.buttonsView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import com.afbb.preferencessample.R;
import com.example.buttonsView.TwoButtons.ButtonClickEvents;
public class MainActivity extends Activity {
TwoButtons buttons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons = (TwoButtons) findViewById(R.id.twoButtons1);
buttons.setOnButtonClickEvent(new ButtonClickEvents() {
#Override
public void redButtonClick() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "red",
Toast.LENGTH_SHORT).show();
}
#Override
public void blueButtonClick() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "blue",
Toast.LENGTH_SHORT).show();
}
});
}
}
output :

paint canvas android

I'm developing in android, and I have to do a Paint for android.
I'm using the code below and, when I execute the code, the draw works, but, it seems that there are 2 surfaces to paint, and when you draw in one, the other one disappears.
I was looking for the exact error, but cannot find it.
Here is the code :
import java.util.Random;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
MySurfaceView mySurfaceView;
Button Cuadrado;
Button Circulo;
Button Color;
Button Linea;
private boolean Bcuadrado,Bcirculo,Bcolor=false;
private boolean Blinea=true;
Canvas canvas = new Canvas();
#TargetApi(11)
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout mainLayout =(RelativeLayout)findViewById(R.id.main_layout_id );
View view =getLayoutInflater().inflate(R.layout.itemlayout, mainLayout,false);
mainLayout.addView(view);
mySurfaceView = new MySurfaceView(this);
Cuadrado=(Button)findViewById(R.id.button1);
Circulo=(Button)findViewById(R.id.button2);
Color=(Button)findViewById(R.id.button3 );
Linea=(Button)findViewById(R.id.button4 );
int w= view.getWidth();
int h= view.getHeight();
float x=view.getX();
float y= view.getY();
mySurfaceView.setY(100);
mainLayout.addView(mySurfaceView);
Cuadrado.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(Bcuadrado==false){
Bcuadrado=true;
Bcirculo=false;
Bcolor=false;
Blinea=false;
}
}
});
Circulo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!Bcirculo){
Bcuadrado=false;
Bcirculo=true;
Bcolor=false;
Blinea=false;
}
}
});
Color.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!Bcolor){
Bcuadrado=false;
Bcirculo=false;
Bcolor=true;
Blinea=false;
}
}
});
Linea.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!Blinea){
Bcuadrado=false;
Bcirculo=false;
Bcolor=false;
Blinea=true;
}
}
});
}
class MySurfaceView extends SurfaceView{
Path path;
SurfaceHolder surfaceHolder;
volatile boolean running = false;
private Paint paint = new Paint();
float x0=0;
float x1=0;
float y0=0;
float y1=0;
Random random = new Random();
public MySurfaceView(Context context) {
super(context);
surfaceHolder = getHolder();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
paint.setColor(android.graphics.Color.WHITE);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(Blinea){
if(event.getAction() == MotionEvent.ACTION_DOWN){
path = new Path();
path.moveTo(event.getX(), event.getY());
}else if(event.getAction() == MotionEvent.ACTION_MOVE){
path.lineTo(event.getX(), event.getY());
}else if(event.getAction() == MotionEvent.ACTION_UP){
path.lineTo(event.getX(), event.getY());
}
if(path != null){
canvas = surfaceHolder.lockCanvas();
canvas.drawPath(path, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}else if(Bcuadrado){
if(event.getAction()==MotionEvent.ACTION_DOWN){
x0=event.getX();
y0=event.getY();
}
else if(event.getAction()==MotionEvent.ACTION_UP){
x1=event.getX();
y1=event.getY();
canvas = surfaceHolder.lockCanvas();
canvas.drawRect(x0, y0, x1, y1, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}else if(Bcirculo){
if(event.getAction()==MotionEvent.ACTION_DOWN){
x0=event.getX();
y0=event.getY();
}
else if(event.getAction()==MotionEvent.ACTION_UP){
x1=event.getX();
canvas=surfaceHolder.lockCanvas();
canvas.drawCircle(x0, y0,(x1-x0), paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}else if(Bcolor){
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
canvas=surfaceHolder.lockCanvas();
paint.setColor(0xff000000 + (r << 16) + (g << 8) + b);
surfaceHolder.unlockCanvasAndPost(canvas);
}
return true;
}
}
}
it seems that there are 2 surfaces to paint, and when you draw in one, the other one disappears.
That is exactly how SurfaceView works - it's double buffered. You need to redraw whole frame each time.
From Android's doc: SurfaceHolder
The content of the Surface is never preserved between unlockCanvas() and lockCanvas(), for this reason, every pixel within the Surface area must be written. The only exception to this rule is when a dirty rectangle is specified, in which case, non-dirty pixels will be preserved.
The canvas does not save what you previously wrote to it. Every time you call unlock(), you must redraw everything all over again.

How to rotate image with fix point along with touch in android

I've been looking for over a day for a solution to this problem but nothing helped, even the answers here didn't helped me.
my problem is my image is rotating but bitmap size is not varying while rotating.
here is my code
package dharam.rotate;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
public class Rotate extends Activity {
View baseView ;
ImageView turntable;
TextView bottomText;
GestureDetector gestureDetector;
private float x , y;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
baseView = (View) findViewById(R.id.baseView);
turntable = (ImageView) findViewById(R.id.turntable);
turntable.setOnTouchListener(onTableTouched);
baseView.setOnTouchListener(onTableTouched);
}
public android.view.View.OnTouchListener onTableTouched = new android.view.View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent evt) {
double r = Math.atan2(evt.getX() - turntable.getWidth() / 2,
(turntable.getHeight() / 2) - evt.getY());
int rotation = (int) Math.toDegrees(r);
Log.i("R is ", ""+r);
if (evt.getAction() == MotionEvent.ACTION_DOWN) {
}
if (evt.getAction() == MotionEvent.ACTION_MOVE) {
x= evt.getX();
y= evt.getY();
updateRotation(rotation);
}
if (evt.getAction() == MotionEvent.ACTION_UP) {
//
}
return true;
}
};
private void updateRotation(double rot) {
float newRot = new Float(rot);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.orsl_circle_transparent);
Matrix matrix = new Matrix();
// matrix.setTranslate(getWindowManager().getDefaultDisplay().getWidth()/2, getWindowManager().getDefaultDisplay().getHeight());
matrix.postRotate(newRot,bitmap.getWidth()/2,bitmap.getHeight()/2);
// matrix.setSinCos(newRot, newRot/2, 100, 100);
// matrix.postRotate(newRot);
Log.i("THE ROATTION ", " "+ newRot);
if(y>250)
{
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap
.getWidth(), bitmap.getHeight(), matrix, true);
turntable.setImageBitmap(redrawnBitmap);
}else
{
Bitmap redrawnBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap
.getWidth(), bitmap.getHeight(), matrix, true);
turntable.setImageBitmap(redrawnBitmap);
Log.i("GUITAR _IMAGE", "");
}
}
}
I presume you want to rotate an image at the point where a user touches the screen? If so, extend the SimpleOnGestureListener like this example:
public class MyGestureDetector extends SimpleOnGestureListener
{
#Override
public void onLongPress(MotionEvent event)
{
int X = (int)event.getX();
int Y = (int)event.getY();
...Rotate the image
}
}
Once you've got the screen coordinates of the touch event, you could apply a Rotation Animation about the point - see here for more details: http://developer.android.com/guide/topics/graphics/2d-graphics.html
I checked your code just by not taking the baseview and it works fine. Here is my code and it works fine in my emulator.
package com.android.practice;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class JobSearch extends Activity implements OnTouchListener {
private ImageView dialer;
private float y=0;
public boolean onTouch(View v, MotionEvent event) {
double r=Math.atan2(event.getX()-dialer.getWidth()/2, dialer.getHeight()/2-event.getY());
int rotation=(int)Math.toDegrees(r);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
//x=event.getX();
y=event.getY();
updateRotation(rotation);
break;
case MotionEvent.ACTION_UP:
break;
}//switch
return true;
}//onTouch
private void updateRotation(double rot){
float newRot=new Float(rot);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.round_button_big);
Matrix matrix=new Matrix();
matrix.postRotate(newRot,bitmap.getWidth()/2,bitmap.getHeight()/2);
if(y>250){
Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
dialer.setImageBitmap(reDrawnBitmap);
}
else{
Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
dialer.setImageBitmap(reDrawnBitmap);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialer = (ImageView) findViewById(R.id.big_button);
dialer.setOnTouchListener(this);
}//onCreate
}

Categories

Resources