Android的画布绘制矩形

Android的画布绘制矩形

本文介绍了使用ontouch Android的画布绘制矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要绘制与ontouch事件点在画布上的矩形。我得到了矩形的工作,但是当我画另一个矩形previous矩形消失。我想我需要矩形点存储在阵列一些。请建议我的一些想法。

到目前为止,我的code是如下:

先在视图类ontouch方法

 私人无效onTouchEvent(MotionEvent事件){
    xTouchCoordinate = event.getX();
    yTouchCoordinate = event.getY();
 如果(event.getAction()== MotionEvent.ACTION_DOWN){
        isActionUp = FALSE;
        pushState的();        运行startx = event.getX();
        startY = event.getY();
 }
否则如果(event.getAction()== MotionEvent.ACTION_UP){
isActionUp = TRUE;
}
否则如果(event.getAction()== MotionEvent.ACTION_MOVE){
        isActionUp = FALSE;
如果(mTouchMode == TouchModes.RECT​​ANGLE)
        {
            updateRectPath(运行startx,startY,xTouchCoordinate,yTouchCoordinate);        }
}
}

和的onDraw方法

 保护无效的onDraw(帆布油画){
    ImageObject.setInteractiveMode(真);
    INT SC = canvas.save();
    canvas.drawColor(Color.BLACK);
    canvas.scale(mCanvasScale,mCanvasScale);
    canvas.translate(mCanvasOffset.x,mCanvasOffset.y);
    canvas.cli preCT(mCanvasLimits);
    canvas.drawColor(Color.WHITE);    如果(currentState.drawGrid)
        drawGridLines(画布);
    drawImages(帆布,真);
    drawLines(画布);
    drawRectangles(画布);
    drawCircles(画布);
    drawOvals(画布);
    drawImages(帆布,FALSE);
    }

DrawRectangles方法

 私人无效drawRectangles(帆布油画){
    尝试
    {
        如果(路径!= NULL)
        {
            如果(mTouchMode == TouchModes.RECT​​ANGLE)
            {                    finishPath(画布);
            }
        }
    }赶上(例外五)
    {    }}

finishpath方法

 无效finishPath(帆布油画){
    如果(mTouchMode == TouchModes.RECT​​ANGLE)
    {
        油漆=新的油漆();        paint.setAntiAlias​​(真);
        paint.setDither(真);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(currentState.currentColor);
        paint.setFlags(Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap​​(Paint.Cap.ROUND);
        paint.setStrokeWidth(currentStrokeWidth);        canvas.drawPath(路径,油漆);    }
}
 无效updateRectPath(浮点X1,Y1浮球,浮球X2,Y2浮动){
    path.rewind();
    X1 = X1 - mCanvasOffset.x;
    Y1 = Y1 - mCanvasOffset.y;
    X2 = X2 - mCanvasOffset.x;
    Y2 = Y2 - mCanvasOffset.y;
    翻译(X1,Y1);
    Log.d(X1为+ X1,Y1为+ Y1);
    如果(X1< X 2安培;&安培; Y1> Y2){
        path.addRect(X1,Y2,X2,Y1,Path.Direction.CW);
    }
    如果(X1< X 2安培;&安培; Y1< Y2){
        path.addRect(X1,Y1,X2,Y2,Path.Direction.CW);
    }
    如果(X1> X2和放大器;&安培; Y1> Y2){
        path.addRect(X2,Y2,X1,Y1,Path.Direction.CW);
    }
    如果(X1> X2和放大器;&安培; Y1< Y2){
        path.addRect(X2,Y1,X1,Y2,Path.Direction.CW);
    }}


解决方案

 如果你有apidemos源$ C ​​$ C(或可以找到互联网上),它有一个fingerpaint例如code。可以参考的是:在任何情况下,我在这里粘贴code ../ *
 *版权所有(C)2007年Android开源项目
 *
 *在Apache许可,2.0版(以下简称许可证);
 *您不能使用这个文件除了在遵守许可。
 *您可以在获得许可证的副本
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意,软件
 *许可下发布的分布在原样的基础,
 *无担保或任何形式的条件,无论是前preSS或暗示的保证。
 *请参阅许可证的特定语言的管理权限和
 *根据许可证的限制。
 * /包com.example.android.apis.graphics;进口android.content.Context;
进口android.graphics *。
进口android.os.Bundle;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.MotionEvent;
进口android.view.View;公共类FingerPaint扩展GraphicsActivity
        实现ColorPickerDialog.OnColorChangedListener {    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(新MyView的(本));        mPaint =新的油漆();
        mPaint.setAntiAlias​​(真);
        mPaint.setDither(真);
        mPaint.setColor(0xFFFF0000地址);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap​​(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(12);        mEmboss =新EmbossMaskFilter(新浮法[] {1,1,1},
                                       0.4f,6,3.5F);        运动模糊=新BlurMaskFilter(8 BlurMaskFilter.Blur.NORMAL);
    }    私人涂料mPaint;
    私人MaskFilter将mEmboss;
    私人MaskFilter将运动模糊;    公共无效colorChanged(INT颜色){
        mPaint.setColor(颜色);
    }    公共类MyView的扩展视图{        私有静态最终浮动MINP = 0.25f;
        私有静态最终浮动MAXP = 0.75f​​;        私人位图mBitmap;
        私人帆布mCanvas;
        私人路径的mpath;
        私人涂料mBitmapPaint;        公共MyView的(语境C){
            超(C);            的mpath =新路径();
            mBitmapPaint =新的油漆(Paint.DITHER_FLAG);
        }        @覆盖
        保护无效onSizeChanged(INT W,INT小时,INT oldw,诠释oldh){
            super.onSizeChanged(W,H,oldw,oldh);
            mBitmap = Bitmap.createBitmap(W,H,Bitmap.Config.ARGB_8888);
            mCanvas =新的Canvas(mBitmap);
        }        @覆盖
        保护无效的onDraw(帆布油画){
            canvas.drawColor(0xFFAAAAAA);            canvas.drawBitmap(mBitmap,0,0,mBitmapPaint);            canvas.drawPath(的mpath,mPaint);
        }        私人浮动MX,我的;
        私有静态最终浮动TOUCH_TOLERANCE = 4;        私人无效touch_start(浮法X,浮法Y){
            mPath.reset();
            mPath.moveTo(X,Y);
            MX = X;
            我= Y;
        }
        私人无效TOUCH_MOVE(浮法X,浮法Y){
            浮DX = Math.abs(X - MX);
            浮DY = Math.abs(Y - 我的);
            如果(DX> = || TOUCH_TOLERANCE DY> = TOUCH_TOLERANCE){
                mPath.quadTo(MX,MY,(X + MX)/ 2,(Y + MY)/ 2);
                MX = X;
                我= Y;
            }
        }
        私人无效touch_up(){
            mPath.lineTo(MX,我的);
            //提交的路径,我们的屏幕外
            mCanvas.drawPath(的mpath,mPaint);
            //杀死这个,所以我们不要双击平局
            mPath.reset();
        }        @覆盖
        公共布尔onTouchEvent(MotionEvent事件){
            浮X = event.getX();
            浮Y = event.getY();            开关(event.getAction()){
                案例MotionEvent.ACTION_DOWN:
                    touch_start(X,Y​​);
                    无效();
                    打破;
                案例MotionEvent.ACTION_MOVE:
                    TOUCH_MOVE(X,Y);
                    无效();
                    打破;
                案例MotionEvent.ACTION_UP:
                    润色();
                    无效();
                    打破;
            }
            返回true;
        }
    }    私有静态最终诠释COLOR_MENU_ID = Menu.FIRST;
    私有静态最终诠释EMBOSS_MENU_ID = Menu.FIRST + 1;
    私有静态最终诠释BLUR_MENU_ID = Menu.FIRST + 2;
    私有静态最终诠释ERASE_MENU_ID = Menu.FIRST + 3;
    私有静态最终诠释SRCATOP_MENU_ID = Menu.FIRST + 4;    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        super.onCreateOptionsMenu(菜单);        menu.add(0,COLOR_MENU_ID,0,颜色)setShortcut('3','c')中。
        menu.add(0,EMBOSS_MENU_ID,0,浮雕)setShortcut('4','S');
        menu.add(0,BLUR_MENU_ID,0,模糊)setShortcut('5','Z')。
        menu.add(0,ERASE_MENU_ID,0,清除)setShortcut('5','Z')。
        menu.add(0,SRCATOP_MENU_ID,0,SrcATop)setShortcut('5','Z')。        / ****这是该机制与滤镜效果延长?
        意向意图=新意图(NULL,getIntent()的getData());
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(
                              Menu.ALTERNATIVE,0,
                              新组件名(这一点,NotesList.class)
                              空,意向,0,NULL);
        ***** /
        返回true;
    }    @覆盖
    prepareOptionsMenu(菜单菜单)上公共布尔{
        super.on prepareOptionsMenu(菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        mPaint.setXfermode(NULL);
        mPaint.setAlpha(0xFF的);        开关(item.getItemId()){
            案例COLOR_MENU_ID:
                新ColorPickerDialog(这个,这​​个,mPaint.getColor())显示()。
                返回true;
            案例EMBOSS_MENU_ID:
                如果(mPaint.getMaskFilter()!= mEmboss){
                    mPaint.setMaskFilter(mEmboss);
                }其他{
                    mPaint.setMaskFilter(NULL);
                }
                返回true;
            案例BLUR_MENU_ID:
                如果(mPaint.getMaskFilter()!=运动模糊){
                    mPaint.setMaskFilter(运动模糊);
                }其他{
                    mPaint.setMaskFilter(NULL);
                }
                返回true;
            案例ERASE_MENU_ID:
                mPaint.setXfermode(新PorterDuffXfermode(
                                                        PorterDuff.Mode.CLEAR));
                返回true;
            案例SRCATOP_MENU_ID:
                mPaint.setXfermode(新PorterDuffXfermode(
                                                    PorterDuff.Mode.SRC_ATOP));
                mPaint.setAlpha(0x80的);
                返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }
}

I need to draw a rectangle on the canvas with points from ontouch events. i got the rectangle shape working but when i draw another rectangle the previous rectangle disappears. I think i need to store the rectangle points in some array. please suggest me some ideas.

So far my code is as follows.

first in ontouch method in view class

private void onTouchEvent(MotionEvent event) {
    xTouchCoordinate = event.getX();
    yTouchCoordinate = event.getY();
 if (event.getAction() == MotionEvent.ACTION_DOWN) {
        isActionUp = false;
        pushState ();

        startX = event.getX();
        startY = event.getY();
 }
else if (event.getAction() == MotionEvent.ACTION_UP) {
isActionUp = true;
}
else if (event.getAction() == MotionEvent.ACTION_MOVE){
        isActionUp = false;
if(mTouchMode == TouchModes.RECTANGLE )
        {
            updateRectPath(startX,startY , xTouchCoordinate , yTouchCoordinate);

        }
}
}

and onDraw method is

 protected void onDraw(Canvas canvas) {
    ImageObject.setInteractiveMode(true);
    int sc = canvas.save();
    canvas.drawColor(Color.BLACK);
    canvas.scale(mCanvasScale, mCanvasScale);
    canvas.translate(mCanvasOffset.x, mCanvasOffset.y);
    canvas.clipRect(mCanvasLimits);
    canvas.drawColor(Color.WHITE);

    if (currentState.drawGrid)
        drawGridLines (canvas);
    drawImages (canvas, true);
    drawLines (canvas);
    drawRectangles(canvas);
    drawCircles(canvas);
    drawOvals(canvas);
    drawImages (canvas, false);
    }

DrawRectangles method

 private void drawRectangles(Canvas canvas) {
    try
    {
        if(path!=null)
        {
            if(mTouchMode == TouchModes.RECTANGLE)
            {

                    finishPath(canvas);
            }
        }
    }catch(Exception e)
    {

    }

}

finishpath method

void finishPath(Canvas canvas) {




    if(mTouchMode == TouchModes.RECTANGLE)
    {
        paint = new Paint();

        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(currentState.currentColor);
        paint.setFlags(Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(currentStrokeWidth);

        canvas.drawPath(path, paint);

    }
}


 void updateRectPath(float x1, float y1, float x2, float y2) {
    path.rewind();
    x1 = x1 - mCanvasOffset.x;
    y1 = y1 - mCanvasOffset.y;
    x2 = x2 - mCanvasOffset.x;
    y2 = y2 - mCanvasOffset.y;
    translate(x1, y1);
    Log.d ("x1 is "+x1, "y1 is "+y1);


    if (x1 < x2 && y1 > y2) {
        path.addRect(x1, y2, x2, y1, Path.Direction.CW);
    }
    if (x1 < x2 && y1 < y2) {
        path.addRect(x1, y1, x2, y2, Path.Direction.CW);
    }
    if (x1 > x2 && y1 > y2) {
        path.addRect(x2, y2, x1, y1, Path.Direction.CW);
    }
    if (x1 > x2 && y1 < y2) {
        path.addRect(x2, y1, x1, y2, Path.Direction.CW);
    }



}
解决方案
Hi if you have the source code of apidemos (or can find on internet), it has a fingerpaint example code. you can refer that: In any case i am pasting the code here..

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.graphics;

import android.content.Context;
import android.graphics.*;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

public class FingerPaint extends GraphicsActivity
        implements ColorPickerDialog.OnColorChangedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFFFF0000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(12);

        mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 },
                                       0.4f, 6, 3.5f);

        mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
    }

    private Paint       mPaint;
    private MaskFilter  mEmboss;
    private MaskFilter  mBlur;

    public void colorChanged(int color) {
        mPaint.setColor(color);
    }

    public class MyView extends View {

        private static final float MINP = 0.25f;
        private static final float MAXP = 0.75f;

        private Bitmap  mBitmap;
        private Canvas  mCanvas;
        private Path    mPath;
        private Paint   mBitmapPaint;

        public MyView(Context c) {
            super(c);

            mPath = new Path();
            mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(0xFFAAAAAA);

            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

            canvas.drawPath(mPath, mPaint);
        }

        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        private void touch_start(float x, float y) {
            mPath.reset();
            mPath.moveTo(x, y);
            mX = x;
            mY = y;
        }
        private void touch_move(float x, float y) {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
                mX = x;
                mY = y;
            }
        }
        private void touch_up() {
            mPath.lineTo(mX, mY);
            // commit the path to our offscreen
            mCanvas.drawPath(mPath, mPaint);
            // kill this so we don't double draw
            mPath.reset();
        }

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

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    touch_start(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_MOVE:
                    touch_move(x, y);
                    invalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    touch_up();
                    invalidate();
                    break;
            }
            return true;
        }
    }

    private static final int COLOR_MENU_ID = Menu.FIRST;
    private static final int EMBOSS_MENU_ID = Menu.FIRST + 1;
    private static final int BLUR_MENU_ID = Menu.FIRST + 2;
    private static final int ERASE_MENU_ID = Menu.FIRST + 3;
    private static final int SRCATOP_MENU_ID = Menu.FIRST + 4;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
        menu.add(0, EMBOSS_MENU_ID, 0, "Emboss").setShortcut('4', 's');
        menu.add(0, BLUR_MENU_ID, 0, "Blur").setShortcut('5', 'z');
        menu.add(0, ERASE_MENU_ID, 0, "Erase").setShortcut('5', 'z');
        menu.add(0, SRCATOP_MENU_ID, 0, "SrcATop").setShortcut('5', 'z');

        /****   Is this the mechanism to extend with filter effects?
        Intent intent = new Intent(null, getIntent().getData());
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(
                              Menu.ALTERNATIVE, 0,
                              new ComponentName(this, NotesList.class),
                              null, intent, 0, null);
        *****/
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        mPaint.setXfermode(null);
        mPaint.setAlpha(0xFF);

        switch (item.getItemId()) {
            case COLOR_MENU_ID:
                new ColorPickerDialog(this, this, mPaint.getColor()).show();
                return true;
            case EMBOSS_MENU_ID:
                if (mPaint.getMaskFilter() != mEmboss) {
                    mPaint.setMaskFilter(mEmboss);
                } else {
                    mPaint.setMaskFilter(null);
                }
                return true;
            case BLUR_MENU_ID:
                if (mPaint.getMaskFilter() != mBlur) {
                    mPaint.setMaskFilter(mBlur);
                } else {
                    mPaint.setMaskFilter(null);
                }
                return true;
            case ERASE_MENU_ID:
                mPaint.setXfermode(new PorterDuffXfermode(
                                                        PorterDuff.Mode.CLEAR));
                return true;
            case SRCATOP_MENU_ID:
                mPaint.setXfermode(new PorterDuffXfermode(
                                                    PorterDuff.Mode.SRC_ATOP));
                mPaint.setAlpha(0x80);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

这篇关于使用ontouch Android的画布绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 14:22