Click here to Skip to main content
15,867,871 members
Home / Discussions / Android
   

Android

 
GeneralRe: I want to program an application to search for contacts by name or phone number use java or kotlin or flutter Pin
Dave Kreskowiak16-Nov-22 1:34
mveDave Kreskowiak16-Nov-22 1:34 
QuestionHow to create a centralized messaging system? Pin
el chupino23-May-22 4:04
el chupino23-May-22 4:04 
AnswerRe: How to create a centralized messaging system? Pin
Richard MacCutchan23-May-22 4:41
mveRichard MacCutchan23-May-22 4:41 
QuestionWhats the best way to get others involved in a project app? Pin
Jstavene7-Apr-22 19:45
Jstavene7-Apr-22 19:45 
AnswerRe: Whats the best way to get others involved in a project app? Pin
Member 1551036025-Apr-22 1:56
Member 1551036025-Apr-22 1:56 
AnswerRe: Whats the best way to get others involved in a project app? Pin
rareprob solutions6-Oct-22 0:36
rareprob solutions6-Oct-22 0:36 
QuestionXAMARIN Android Access to DB2 Pin
Member 1180022822-Mar-22 23:47
Member 1180022822-Mar-22 23:47 
QuestionCustom drawing view with tools Pin
Cristo198524-Feb-22 20:38
Cristo198524-Feb-22 20:38 
Hi,
i need a little help.

I'm creating my custom Drawing View.

The functionality I am trying to achieve is:

Arrow icon => touch one point and drag until other point draws line-arrow

Text icon => touch in one point of screen and enter a text (open keyboard and write and close it)

Eraser icon => erase canvas drawn

These is the design of the menu I've made:

TOOLS MENU

And all interface is here:

INTERFACE

How can I edit my custom drawing view for make tools specified above? Whick portion of code will I put inside CustomDrawingView class?

Here my DrawingView class:

Java
public class DrawingView extends View
{
    private Path mDrawPath;
    private Paint mBackgroundPaint;
    private Paint mDrawPaint;
    private Canvas mDrawCanvas;
    private Bitmap mCanvasBitmap;

    private ArrayList<Path> mPaths = new ArrayList<>();
    private ArrayList<Paint> mPaints = new ArrayList<>();
    private ArrayList<Path> mUndonePaths = new ArrayList<>();
    private ArrayList<Paint> mUndonePaints = new ArrayList<>();

    // Set default values
    private int mBackgroundColor = 0x00FFFFFF;
    private int mPaintColor = 0x00660000;
    private int mStrokeWidth = 10;

    public DrawingView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }

    private void init()
    {
        mDrawPath = new Path();
        mBackgroundPaint = new Paint();
        initPaint();
    }

    private void initPaint()
    {
        mDrawPaint = new Paint();
        mDrawPaint.setColor(mPaintColor);
        mDrawPaint.setAntiAlias(true);
        mDrawPaint.setStrokeWidth(mStrokeWidth);
        mDrawPaint.setStyle(Paint.Style.STROKE);
        mDrawPaint.setStrokeJoin(Paint.Join.ROUND);
        mDrawPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    private void drawBackground(Canvas canvas)
    {
        mBackgroundPaint.setColor(Color.TRANSPARENT);
        mBackgroundPaint.setAntiAlias(true);
        mBackgroundPaint.setAlpha(0);
        canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), mBackgroundPaint);

    }

    private void drawPaths(Canvas canvas)
    {
        int i = 0;
        for (Path p : mPaths)
        {
            canvas.drawPath(p, mPaints.get(i));
            i++;
        }
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        drawBackground(canvas);
        drawPaths(canvas);

        canvas.drawPath(mDrawPath, mDrawPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);

        mCanvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        mDrawCanvas = new Canvas(mCanvasBitmap);
    }




    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        float touchX = event.getX();
        float touchY = event.getY();

        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                Log.d("Debug", "TOUCH EVENT: ACTION_DOWN");
                mDrawPath.moveTo(touchX, touchY);
                break;
            case MotionEvent.ACTION_MOVE:
                Log.d("Debug", "TOUCH EVENT: ACTION_DOWN");
                mDrawPath.lineTo(touchX, touchY);
                break;
            case MotionEvent.ACTION_UP:
                Log.d("Debug", "TOUCH EVENT: ACTION_DOWN");
                mDrawPath.lineTo(touchX, touchY);
                mPaths.add(mDrawPath);
                mPaints.add(mDrawPaint);
                mDrawPath = new Path();
                initPaint();
                break;
            default:
                return false;
        }

        invalidate();
        return true;
    }

    public void clearCanvas()
    {
        mPaths.clear();
        mPaints.clear();
        mUndonePaths.clear();
        mUndonePaints.clear();
        mDrawCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        invalidate();
    }

    public void startEraser()
    {
        Log.d("Drawingview", "StartEraser");
        mDrawPaint.setXfermode(null);
        mDrawPaint.setAlpha(0xFF);
        mDrawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

    }

    public void setPaintColor(int color)
    {
        mPaintColor = color;
        mDrawPaint.setColor(mPaintColor);
    }

    public void setPaintStrokeWidth(int strokeWidth)
    {
        mStrokeWidth = strokeWidth;
        mDrawPaint.setStrokeWidth(mStrokeWidth);
    }

    public void setBackgroundColor(int color)
    {
        mBackgroundColor = color;
        mBackgroundPaint.setColor(mBackgroundColor);
        invalidate();
    }



    public Bitmap getBitmap()
    {
        drawBackground(mDrawCanvas);
        drawPaths(mDrawCanvas);
        return mCanvasBitmap;
    }

    public void undo()
    {
        if (mPaths.size() > 0)
        {
            mUndonePaths.add(mPaths.remove(mPaths.size() - 1));
            mUndonePaints.add(mPaints.remove(mPaints.size() - 1));
            invalidate();
        }
    }


    public void redo()
    {
        if (mUndonePaths.size() > 0)
        {
            mPaths.add(mUndonePaths.remove(mUndonePaths.size() - 1));
            mPaints.add(mUndonePaints.remove(mUndonePaints.size() - 1));
            invalidate();
        }
    }
}


And this is my interface (as see in picture) class:
Java
<pre>public class Board1 extends AppCompatActivity {
private TextView titolo;
private DrawingView areaDisegno;
private ImageView testo, freccia, sceltaColore, sceltaSpessore, undo, redo;
private Bitmap drawable;

private boolean isEnabledManoLibera = true;
private boolean isEnabledLinea = false;
private boolean isEnabledArrow = false;

public ImageButton menuButton;


private int mCurrentBackgroundColor;
private int mCurrentColor;
private int mCurrentStroke;
private static final int MAX_STROKE_WIDTH = 50;

@Override
protected void onCreate(Bundle savedInstanceState) {
    supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.black));
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_board1);

    menuButton = findViewById(R.id.menu_button);

    menuButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Creating the instance of PopupMenu
            PopupMenu popup = new PopupMenu( Board1.this, menuButton);
            //Inflating the Popup using xml file
            popup.getMenuInflater()
                    .inflate(R.menu.menu, popup.getMenu());

            //registering popup with OnMenuItemClickListener
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getTitle().toString())
                    {
                        case "Match Up":
                            CaricaMainActivity("TabellaMatchUp");
                            break;
                        case "Match Board":
                            CaricaMainActivity("SceltaBoards");
                            break;
                        case "Match Book":
                            CaricaMainActivity("InfoBook");
                            break;
                    }
                    return true;
                }
            });

            popup.show(); //showing popup menu
        }
    });

    titolo = findViewById(R.id.titolo);

    titolo.setText("MATCHUP BOARD 1");

    areaDisegno = findViewById(R.id.area_disegno);
    testo = findViewById(R.id.testo);
    freccia = findViewById(R.id.freccia);
    sceltaColore= findViewById(R.id.scelta_colore);
    sceltaSpessore = findViewById(R.id.scelta_spessore);
    undo = findViewById(R.id.undo);
    redo = findViewById(R.id.redo);

    testo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           isEnabledArrow = false;
           isEnabledLinea = false;
           isEnabledManoLibera = false;
        }
    });

    freccia.setOnClickListener(new View.OnClickListener() {
                                   @Override
                                   public void onClick(View v) {
                                       isEnabledArrow = true;
                                       isEnabledLinea = false;
                                       isEnabledManoLibera = false;
                                   }
                               });

    sceltaColore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startColorPickerDialog();
        }
    });

    sceltaSpessore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startStrokeSelectorDialog();
        }
    });

    undo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            areaDisegno.undo();
        }
    });

    redo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            areaDisegno.redo();;
        }
    });



    inizializzaAreaDisegno();


}

public void CaricaMainActivity(String todo)
{
    Intent mainActivity = new Intent(Board1.this, MainActivity.class);
    mainActivity.putExtra("todo", todo);
    startActivity(mainActivity);
    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}

private void inizializzaAreaDisegno()
{
 //   mCurrentBackgroundColor = ContextCompat.getColor(this, android.R.color.white);
    mCurrentColor = ContextCompat.getColor(this, android.R.color.black);
    mCurrentStroke = 10;

    areaDisegno.setBackgroundColor(mCurrentBackgroundColor);
    areaDisegno.setPaintColor(mCurrentColor);
    areaDisegno.setPaintStrokeWidth(mCurrentStroke);
}


private void startColorPickerDialog()
{
    int[] colors = getResources().getIntArray(R.array.palette);
    String[] nomiColori = getResources().getStringArray(R.array.palette_colori);

    ColorPickerDialog dialog = ColorPickerDialog.newInstance(R.string.color_picker_default_title,
    colors,
    mCurrentColor,
    6,
    ColorPickerDialog.SIZE_SMALL);


    dialog.setOnColorSelectedListener(new ColorPickerSwatch.OnColorSelectedListener()
    {
        @Override
        public void onColorSelected(int color)
        {
            int position = ArrayUtils.getArrayIndex(colors, color);

            mCurrentColor = color;
            areaDisegno.setPaintColor(mCurrentColor);
            Log.d("DEBUG","Colore Scelto: " + mCurrentColor);
            sceltaColore.setBackground(getDrawableByName(nomiColori[position], getApplicationContext()));
        }

    });


    dialog.show(getFragmentManager(), "ColorPickerDialog");



}

public static Drawable getDrawableByName(String name, Context context) {
    int drawableResource = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
    if (drawableResource == 0) {
        throw new RuntimeException("Can't find drawable with name: " + name);
    }//w  w  w  .j  ava  2 s  .co  m
    return context.getResources().getDrawable(drawableResource);
}

private void startStrokeSelectorDialog()
{
    StrokeSelectorDialog dialog = StrokeSelectorDialog.newInstance(mCurrentStroke, MAX_STROKE_WIDTH);

    dialog.setOnStrokeSelectedListener(new StrokeSelectorDialog.OnStrokeSelectedListener()
    {
        @Override
        public void onStrokeSelected(int stroke)
        {
            mCurrentStroke = stroke;
            areaDisegno.setPaintStrokeWidth(mCurrentStroke);
        }
    });

    dialog.show(getSupportFragmentManager(), "StrokeSelectorDialog");
}

private void startShareDialog(Uri uri)
{
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");

    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
    intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(intent, "Share Image"));
}

private void requestPermissionsAndSaveBitmap()
{
    if (PermissionManager.checkWriteStoragePermissions(this))
    {
        Uri uri = FileManager.saveBitmap(this, areaDisegno.getBitmap());
        startShareDialog(uri);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case PermissionManager.REQUEST_WRITE_STORAGE:
        {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Uri uri = FileManager.saveBitmap(this, areaDisegno.getBitmap());
                startShareDialog(uri);
            } else
            {
                Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }
}

public static Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = null;

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
} } // end of class


I've tried to add this method inside Drawing View class:


Java
public void drawText(String testo)
   {
       mDrawPaint.setColor(Color.WHITE);
       mDrawPaint.setTextSize(200);
       mDrawCanvas.drawText(testo, 10, 25, mDrawPaint);
       invalidate();
   }


But when i call this method can't see add text...

Thanks for any help. Cris

QuestionRe: Custom drawing view with tools Pin
David Crow25-Feb-22 5:22
David Crow25-Feb-22 5:22 
AnswerRe: Custom drawing view with tools Pin
Cristo198527-Feb-22 5:52
Cristo198527-Feb-22 5:52 
GeneralRe: Custom drawing view with tools Pin
Mycroft Holmes27-Feb-22 11:32
professionalMycroft Holmes27-Feb-22 11:32 
Questionhow to upload apps on google playstore Pin
Bimbel Tahsin 7-Feb-22 4:03
professionalBimbel Tahsin 7-Feb-22 4:03 
SuggestionRe: how to upload apps on google playstore Pin
David Crow25-Feb-22 5:13
David Crow25-Feb-22 5:13 
AnswerRe: how to upload apps on google playstore Pin
Member 1551036026-Apr-22 2:17
Member 1551036026-Apr-22 2:17 
GeneralRe: how to upload apps on google playstore Pin
Matthew Daniel11-Sep-22 19:13
Matthew Daniel11-Sep-22 19:13 
Questionc# Appium Android Search Key is not working Pin
subinrajuu2-Feb-22 20:29
subinrajuu2-Feb-22 20:29 
AnswerRe: c# Appium Android Search Key is not working Pin
Richard Deeming2-Feb-22 21:42
mveRichard Deeming2-Feb-22 21:42 
Questionandroid studio code in java to do biblle app Pin
Dereje Bodena25-Jan-22 20:39
Dereje Bodena25-Jan-22 20:39 
RantRe: android studio code in java to do biblle app Pin
Richard Deeming25-Jan-22 21:54
mveRichard Deeming25-Jan-22 21:54 
QuestionANDROID STUDIO The System cannot find the path specified Pin
Saboor880217-Jan-22 2:56
Saboor880217-Jan-22 2:56 
QuestionXamarin Forms INavigation Pin
Kevin Marois6-Jan-22 11:20
professionalKevin Marois6-Jan-22 11:20 
QuestionE-Wallet App Development Pin
zoey laurance22-Nov-21 2:36
zoey laurance22-Nov-21 2:36 
AnswerRe: E-Wallet App Development Pin
OriginalGriff22-Nov-21 2:38
mveOriginalGriff22-Nov-21 2:38 
GeneralRe: E-Wallet App Development Pin
Richard Deeming22-Nov-21 2:54
mveRichard Deeming22-Nov-21 2:54 
GeneralRe: E-Wallet App Development Pin
OriginalGriff22-Nov-21 2:59
mveOriginalGriff22-Nov-21 2:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.