I am working on application in which i want to display different text on image.when i touch the different position.I am working on the different image.In my program I have used one class to change the image and one class to draw a text on the image.
my activity class is as follow......
public class VideosActivity extends Activity implements OnTouchListener
{
//DrawView draw;
float a=0;
float b=0;
ImageView image;
MotionEvent event;
Button back ;
Button next;
TextView t;
String info = "";
int count =0;
FirstImage i;
ViewFlipper c;
Infoview v;
String huma="human";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_layout);
i=new FirstImage(this);
c=(ViewFlipper) findViewById(R.id.viewFlipper1);
back = (Button) findViewById(R.id.button1);
next = (Button) findViewById(R.id.button2);
t=(TextView) findViewById(R.id.textView1);
if(count==0)
i.changeImage(R.drawable.human );
i.invalidate();
c.addView(i,0);
c.setOnTouchListener(this);
c.onTouchEvent(event);
}
public void pageinfo(float a,float b)
{
t.setText(Float.toString(a)+"x"+Float.toString(b)+"y");
i.display( a, b);
}
public boolean onTouch(View v, MotionEvent me)
{
// TODO Auto-generated method stub
switch(me.getAction())
{
case MotionEvent.ACTION_DOWN:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_MOVE:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_UP:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
case MotionEvent.ACTION_OUTSIDE:
a=me.getX();
b= me.getY();
pageinfo(a,b);
break;
default: return false;
}
return true;
}
}
the class which is used to change the image is as follow...
public class FirstImage extends LinearLayout {
ImageView i;
int x;
Infoview v;
String huma ="human";
public FirstImage(Context context) {
super(context);
v=new Infoview(context);
i= new ImageView (context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
addView(i, lp);
addView(v,lp);
}
public FirstImage(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void changeImage(int id){
i.setImageResource(id);
x=id;
}
public int getSrc() {
// TODO Auto-generated method stub
return x;
}
public void display(float a, float b) {
// TODO Auto-generated method stub
if(i.getId()==R.drawable.human){
v.updateInfo(huma, a, b);
i.invalidate();
v.invalidate();
}
}
}
class which is used for drawing text on the image is as follow..
public class Infoview extends View {
String info = "";
float x = 0; //init value
float y = 0; //init value
int color = Color.WHITE;
public Infoview(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public Infoview(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public Infoview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setColor(color);
paint.setStrokeWidth(2);
paint.setTextSize(30);
canvas.drawLine(x-10, y, x+10, y, paint);
canvas.drawLine(x, y-10, x, y+10, paint);
canvas.drawText(info, x, y, paint);
}
public void updateInfo(String t_info, float t_x, float t_y){
info = t_info;
x = t_x;
y = t_y;
invalidate();
}
public void clearInfo(){
info = "";
x = 0;
y = 0;
invalidate();
}
I am not understanding why it is not displaying text on the image ......I think in the time of image drawing i am using one layout.so i have to include drawing class(Infoview) into that layout to...
If any one thinking that i am re asking this question then i am sorry ...
any help is appreciated...
I did get time to read the full code but if you override onDraw, you are not supposed to invoke super.onDraw() inside that method since that will mean that the base class will draw everything first.
Related
So I need do one app in Android Studio like Paint
I have this in Myview.Java.
I obtain the coordinates but I can´t save and draw the segment.
I tried with a Vector and I thing Vector is a solution, but isn´t working like I did
public class MyView extends View {
Paint paint = null;
int figure;
public MyView(Context context) {
super(context);
paint = new Paint();
figure = 0;
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
figure = 0;
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
figure = 0;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
if (figure == 1)
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
public void setfigure(int a) {
this.figure = a;
}
}
In MainActivity I have this code
public class MainActivity extends AppCompatActivity {
MyView v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
v = findViewById(R.id.teste);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
//String x1 = "" + x;
TextView textView = (TextView) findViewById(R.id.testecord);
TextView textView2 = (TextView) findViewById(R.id.testecord2);
Ponto2D pinicial = new Ponto2D(Math.round(x), Math.round(y));
Ponto2D pfinal = new Ponto2D(Math.round(x), Math.round(y));
String x1 = "" + pinicial.x;
String x2 = "" + pfinal.x;
textView.setText(x1);
textView2.setText(x2);
int n = 4; // tamanho do vetor
int v[] = new int[n]; // declaração e alocação de espaço para o vetor "v"
int i; // índice ou posição
// processando os "n" elementos do vetor "v"
for (i = 0; i < n; i++) {
v[i] = pinicial.x; // na i-ésima posição do vetor "v" armazena o valor da variável "i"
}
return true;
}
public void f(View vs) {
v.setfigure(1);
v.invalidate();
}
}
I need save the points who user click to draw one straight segment.
I have the code of segment and of Point.
public class Segmento_de_Reta {
Ponto2D pinicial;
Ponto2D pfinal;
String cor;
public Segmento_de_Reta(Ponto2D a, Ponto2D b) {
pinicial = a;
pfinal = b;
}
I am developing an Android drawing app.
When I run this code it says application is doing too much work on it's main thread in logcat.I am not able to draw.PLEASE HELP ME.Thank you
THIS IS MY DRAWIT CLASS
public class Drawit extends Activity {
LinearLayout linearLayout;
ImageButton oclear,save,ocancel;
View mview;
DrawCanvas drawCanvas;
public static String tempDir;
public static String unique_id;
public static String current=null;
public Bitmap mBitmap;
public EditText yourName;
File myPath;
protected void onCreate(Bundle savedInsatnceState) {
// TODO Auto-generated method stub
super.onCreate(savedInsatnceState);
setContentView(R.layout.drawit);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout11);
tempDir = Environment.getExternalStorageDirectory()+"/"+getResources().getString(R.string.external_dir);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory= contextWrapper.getDir(getResources().getString(R.string.external_dir),MODE_PRIVATE);
preparedirectory();
yourName = (EditText) findViewById(R.id.editText1);
myPath = new File(directory,current);
drawCanvas = new DrawCanvas(this, null);
drawCanvas.setBackgroundColor(Color.WHITE);
linearLayout.addView(drawCanvas,LayoutParams.FILL_PARENT);
}
}
THIS IS MY DRAW CANVAS METHOD
public class DrawCanvas extends View
{
public Paint paint = new Paint();
public Path path = new Path();
public final RectF dirtyRect = new RectF();
public float lastTouchX;
public float lastTouchY;
public DrawCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5f);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setAntiAlias(true);
}
protected void ondraw(Canvas canvas) {
canvas.drawPath(path,paint);
}
public void save(View mview) throws IOException{
// TODO Auto-generated method stub
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap(linearLayout.getWidth(),linearLayout.getHeight(),Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try {
FileOutputStream fileoutputstream = new FileOutputStream(myPath);
mview.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG , 90, fileoutputstream);
fileoutputstream.flush();
fileoutputstream.close();
String uri = Images.Media.insertImage(getContentResolver(),mBitmap,"title",null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void clear() {
// TODO Auto-generated method stub
path.reset();
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX,eventY);
int historyRectSize = event.getHistorySize();
for(int i=0;i<historyRectSize;i++)
{
float historicalx = event.getHistoricalX(i);
float historicaly = event.getHistoricalY(i);
expandDirtyRect(historicalx,historicaly);
path.lineTo(historicalx, historicaly);
}
break;
}
return true;
}
private void expandDirtyRect(float historicalx, float historicaly) {
// TODO Auto-generated method stub
if(historicalx < dirtyRect.left)
{
dirtyRect.left = historicalx;
} else if(historicalx >dirtyRect.right)
{
dirtyRect.left = historicalx;
}
if(historicaly < dirtyRect.top)
{
dirtyRect.top = historicaly;
} else if(historicaly >dirtyRect.bottom)
{
dirtyRect.bottom = historicaly;
}
}
private void resetDirtyRect(float eventX, float eventY) {
// TODO Auto-generated method stub
dirtyRect.left = Math.min(lastTouchX,eventX);
dirtyRect.right = Math.max(lastTouchX,eventX);
dirtyRect.top = Math.min(lastTouchY,eventY);
dirtyRect.bottom = Math.max(lastTouchY,eventY);
}
}
}
I am trying to allow the user of my app to paint (with their finger) over a VideoView object.
I have had little success.
In my current attempt, I have tried to put a SurfaceView over a VideoView though I have reached a number of issues: When I open a navigation drawer, the drawings, appear OVER the navigation drawer interface; and the drawings seem to blink on an actual device ( they flash).
This is just my attempt, I am sure there is a better way of allowing the user to paint.
<VideoView
android:id="#+id/videoplayer"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</VideoView>
<com.example.example.VideoOverlay
android:id="#+id/videooverlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Here is the VideoOverlay Class
public class VideoOverlay extends SurfaceView implements Runnable {
Thread thread = null;
SurfaceHolder surfaceHolder;
volatile boolean running = false;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Random random;
public void onResumeMySurfaceView(){
running = true;
thread = new Thread(this);
thread.start();
}
public void onPauseMySurfaceView(){
boolean retry = true;
running = false;
while(retry){
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public VideoOverlay(Context context)
{
super(context);
surfaceHolder = getHolder();
random = new Random();
this.setZOrderMediaOverlay(true);
this.setZOrderOnTop(true);
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
}
public VideoOverlay(Context context, AttributeSet attrs)
{
super(context, attrs);
surfaceHolder = getHolder();
random = new Random();
this.setZOrderMediaOverlay(true);
this.setZOrderOnTop(true);
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
}
public VideoOverlay(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
surfaceHolder = getHolder();
random = new Random();
this.setZOrderMediaOverlay(true);
this.setZOrderOnTop(true);
surfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
}
// Other stuff
#Override
public void run() {
// TODO Auto-generated method stub
while(running){
if(surfaceHolder.getSurface().isValid()){
Canvas canvas = surfaceHolder.lockCanvas();
//... actual drawing on canvas
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
int w = canvas.getWidth();
int h = canvas.getHeight();
int x = random.nextInt(w-1);
int y = random.nextInt(h-1);
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
paint.setColor(0xff000000 + (r << 16) + (g << 8) + b);
canvas.drawPoint(x, y, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
Any help would be great!
Using onDraw, I want to make a custom text view that changes color depending on its text value. For example, if the text value is "hello" I want it to be red and if it says "bye" I want it to be green. Any helps greatly appreciated.
I'm not necessarily sure why you want to do this in onDraw(). Unless you have a really good reason to set up a custom TextView/EditText, that's not necessary.
To simplify your situation, you can implement a TextWatcher to do this, and in onTextChanged(), you can set the color by comparing the string values using .equals().
Here is an example of your theoretical situation:
final EditText yourEditText = /* findViewById maybe? */;
yourEditText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.equalsIgnoreCase("hello"))
yourEditText.setTextColor(Color.RED);
else if (s.equalsIgnoreCase("bye"))
yourEditText.setTextColor(Color.GREEN);
else // if it says neither "hello" nor "bye"
yourEditText.setTextColor(Color.BLACK);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Nothing needs to happen here
}
public void afterTextChanged(Editable s) {
// Nothing needs to happen here
}
});
If you feel its necessary to maintain this in onDraw(), simply extract the code from onTextChanged() and change yourEditText to this, or place it in the constructor instead:
public class YourTextView extends TextView { // Or extends EditText, doesn't matter
public YourTextView(Context context) {
this(context, null, 0);
}
public YourTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public YourTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
addTextChangedListener(new TextWatcher() {
// Copy the TextWatcher code from the example above, replacing "yourEditText" with "YourTextView.this"
});
}
// ... Rest of your class
}
I figured out how to do it in a more creative way using onDraw.
public class MagnitudeTextView extends TextView {
public MagnitudeTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MagnitudeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MagnitudeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
/*
* (non-Javadoc)
*
* #see android.widget.TextView#onDraw(android.graphics.Canvas)
*/
#Override
protected void onDraw(Canvas canvas) {
int height = getMeasuredHeight();
int width = getMeasuredWidth();
int px = width / 2;
int py = height / 2;
Paint Red = new Paint(Paint.ANTI_ALIAS_FLAG);
Red.setColor(Color.RED);
Paint White = new Paint(Paint.ANTI_ALIAS_FLAG);
White.setColor(Color.DKGRAY);
Paint Yellow = new Paint(Paint.ANTI_ALIAS_FLAG);
Yellow.setARGB(210, 105, 30, 0);
Paint Blue = new Paint(Paint.ANTI_ALIAS_FLAG);
Blue.setColor(Color.BLUE);
float textWidth = Red.measureText(String.valueOf(getText()));
String g = String.valueOf(getText());
if (g.startsWith("3") || g.startsWith("4")) {
canvas.drawText(String.valueOf(getText()), px - textWidth / 2, py,
White);
}
if (g.startsWith("6") || g.startsWith("5") || g.startsWith("7")
|| g.startsWith("8")) {
canvas.drawText(String.valueOf(getText()), px - textWidth / 2, py,
Yellow);
}
if (g.startsWith("9") || g.startsWith("10")) {
canvas.drawText(String.valueOf(getText()), px - textWidth / 2, py,
Red);
}
// super.onDraw(canvas);
}
}
You can overwrite setText() and set the color using setTextColor().
You can do it inside onDraw as well, but it's not worth the weigth, as it may pass many times inside onDraw.
You can implement TextWatcher and use onTextChanged()
More about it here in the Android Docs
Use this to get the text:
TextView text = (TextView)findViewById(R.id.textid);
String value = text.getText().toString();
Then check what the text is and change the color :
if (value.equals("hello")) {
text.setBackgroundColor(yourcolor);
}
I have Class which Extends View I'm able To Move one Image Over another For This I use Two Bitmap Image one Over Another now i want to save image's using Double Tap event but i dnt know how to do this....can anyone have some idea or code for this ......
`public class ShowCanvas extends View {
Bitmap CanvasBitmap;
Bitmap ScaledBitmap;
Bitmap smallbitmap;
private static final int INVALID_POINTER_ID = -1;
private Drawable mImage;
private float mPosX;
private float mPosY;
private float mLastTouchX;
private float mLastTouchY;
private int mActivePointerId = INVALID_POINTER_ID;
private ScaleGestureDetector mScaleDetector;
private float mScaleFactor = 1.f;
public ShowCanvas(Context context) {
this(context, null, 0);
// TODO Auto-generated constructor stub
ScaledBitmap = DrawView.scaled;
mImage = new BitmapDrawable(getResources(), Dress.bitmap);
System.out.println("MImage" +mImage);
mImage.setBounds(0, 0, mImage.getIntrinsicWidth(),
mImage.getIntrinsicHeight());
}
public ShowCanvas(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ShowCanvas(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
}
public void setBitmap(Bitmap bitmap) {
// TODO Auto-generated method stub
CanvasBitmap = bitmap;
System.out.println("CanvasBitmap" + CanvasBitmap);
int X = CanvasBitmap.getHeight();
int Y = CanvasBitmap.getWidth();
System.out.println("CanvasBitmap " + X + "\t" + Y);
}
#Override
public boolean isLongClickable() {
// TODO Auto-generated method stub
System.out.println("ISLongClickable");
return super.isLongClickable();
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Let the ScaleGestureDetector inspect all events.
mScaleDetector.onTouchEvent(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
// Only move if the ScaleGestureDetector isn't processing a
// gesture.
if (!mScaleDetector.isInProgress()) {
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
invalidate();
}
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_UP: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
break;
}
}
return true;
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint mpaint = new Paint();
canvas.save();
canvas.drawBitmap(ScaledBitmap, 0, 0, mpaint);
Log.d("DEBUG", "X: " + mPosX + " Y: " + mPosY);
canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor);
mImage.draw(canvas);
canvas.restore();
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
// Don't let the object get too small or too large.
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
invalidate();
return true;
}
}
}`
If you mean double tap you have to use GestureDetector.OnDoubleTapListener. check this link
try this
public class MyView extends View {
GestureDetector gestureDetector;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// creating new gesture detector
gestureDetector = new GestureDetector(context, new GestureListener());
}
// skipping measure calculation and drawing
// delegate the event to the gesture detector
#Override
public boolean onTouchEvent(MotionEvent e) {
return gestureDetector.onTouchEvent(e);
}
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onDown(MotionEvent e) {
return true;
}
// event when double tap occurs
#Override
public boolean onDoubleTap(MotionEvent e) {
float x = e.getX();
float y = e.getY();
Log.d("Double Tap", "Tapped at: (" + x + "," + y + ")");
return true;
}
}
}