美文网首页Android开发
自定义view实现涂鸦(画板)功能(二)

自定义view实现涂鸦(画板)功能(二)

作者: 原来如此丶 | 来源:发表于2016-07-08 11:38 被阅读456次

整理完了,是时候把完整的发出来了

进入正文:
需求修改之后,需要添加画椭圆、画矩形以及画箭头的方法,之后需要将在白色背景上作图改为在图片上进行编辑
总体来说:完成方式类似,只需要在外部设置按钮用标记去标识,在画板中变化画图方式即可

该注释的地方我都加在代码里,所以就不作太多的额外说明了
先定义一下画图方式:

//设置画图样式  
    private static final int DRAW_PATH = 01;  
    private static final int DRAW_CIRCLE = 02;  
    private static final int DRAW_RECTANGLE = 03;  
    private static final int DRAW_ARROW = 04;  
    private int[] graphics = new int[]{DRAW_PATH,DRAW_CIRCLE,DRAW_RECTANGLE,DRAW_ARROW};  
    private  int currentDrawGraphics = graphics[0];//默认画线 

画椭圆和画矩形比较简单:
画椭圆:

if(currentDrawGraphics == DRAW_CIRCLE){  
                mPath.reset();//清空以前的路径,否则会出现无数条从起点到末位置的线  
                RectF rectF = new RectF(startX,startY,x,y);  
                mPath.addOval(rectF, Path.Direction.CCW);//画椭圆  
               // mPath.addCircle((startX + x) / 2, (startY + y) / 2, (float) Math.sqrt(Math.pow(newx, 2) + Math.pow(newy, 2)) / 2, Path.Direction.CCW)//画圆

画矩形:

if(currentDrawGraphics == DRAW_RECTANGLE){  
                mPath.reset();  
                RectF rectF = new RectF(startX,startY,x,y);  
                mPath.addRect(rectF, Path.Direction.CCW); 

稍微麻烦的是画箭头:
思路是:先画线,再以线的另一端为端点按照一个角度来偏移并计算偏移坐标,并得到箭头的两个端点,然后再将端点画线连接起来,这样就会形成一个箭头

if (currentDrawGraphics == DRAW_ARROW){  
                mPath.reset();  
                drawAL((int) startX, (int) startY, (int) x, (int) y);  
}  

drawAL:

/** 
    * 画箭头 
    * @param startX 开始位置x坐标 
    * @param startY 开始位置y坐标 
    * @param endX 结束位置x坐标 
    * @param endY 结束位置y坐标 
    */  
   public void drawAL(int startX, int startY, int endX, int endY)  
   {  
       double lineLength = Math.sqrt(Math.pow(Math.abs(endX-startX),2) + Math.pow(Math.abs(endY-startY),2));//线当前长度  
       double H = 0;// 箭头高度  
       double L = 0;// 箭头长度  
       if(lineLength < 320){//防止箭头开始时过大  
           H = lineLength/4 ;  
           L = lineLength/6;  
       }else { //超过一定线长箭头大小固定  
           H = 80;  
           L = 50;  
       }  
  
       double arrawAngle = Math.atan(L / H); // 箭头角度  
       double arraowLen = Math.sqrt(L * L + H * H); // 箭头的长度  
       double[] pointXY1 = rotateAndGetPoint(endX - startX, endY - startY, arrawAngle, true, arraowLen);  
       double[] pointXY2 = rotateAndGetPoint(endX - startX, endY - startY, -arrawAngle, true, arraowLen);  
       int x3 = (int) (endX - pointXY1[0]);//(x3,y3)为箭头一端的坐标  
       int y3 = (int) (endY - pointXY1[1]);  
       int x4 = (int) (endX - pointXY2[0]);//(x4,y4)为箭头另一端的坐标  
       int y4 = (int) (endY - pointXY2[1]);  
       // 画线  
       mPath.moveTo(startX,startY);  
       mPath.lineTo(endX,endY);  
       mPath.moveTo(x3, y3);  
       mPath.lineTo(endX, endY);  
       mPath.lineTo(x4, y4);  
       // mPath.close();闭合线条  
   }  

rotateAndGetPoint():这个方法就是用来计算箭头端点的,我们需要提供x以及y方向的长度,当然还有箭头偏转角度

/** 
     * 矢量旋转函数,计算末点的位置 
     * @param x  x分量 
     * @param y  y分量 
     * @param ang  旋转角度 
     * @param isChLen  是否改变长度 
     * @param newLen   箭头长度长度 
     * @return    返回末点坐标 
     */  
    public double[] rotateAndGetPoint(int x, int y, double ang, boolean isChLen, double newLen)  
    {  
        double pointXY[] = new double[2];  
        double vx = x * Math.cos(ang) - y * Math.sin(ang);  
        double vy = x * Math.sin(ang) + y * Math.cos(ang);  
        if (isChLen) {  
            double d = Math.sqrt(vx * vx + vy * vy);  
            pointXY[0] = vx / d * newLen;  
            pointXY[1] = vy / d * newLen;  
        }  
        return pointXY;  
    }  

以上通过注释应能比较清晰的看出来思路

之后我就开始着手做成在背景图片上进行涂鸦,这样一来很多东西就需要修改了,原来能在白色背景上做的东西都需要进行修改。
去图库选择图片很简单:

Intent picIntent = new Intent();  
picIntent.setType("image/*");  
picIntent.setAction(Intent.ACTION_GET_CONTENT);  
startActivityForResult(picIntent, OPEN_PHOTO);

但是当你在保存图片时会出现很多各种莫名其妙的错误包括:保存背景为黑色,笔迹完全显示不出来等问题
所以我想的是很可能保存时候没有对图片处理好,决定采用将两张bitmap进行合并的方法,于是就有了:

if(srcBitmap != null){//有背景图  
            Bitmap bitmap = Bitmap.createBitmap(screenWidth,screenHeight, Bitmap.Config.RGB_565);  
            Canvas canvas = new Canvas(bitmap);  
           // canvas.drawBitmap(srcBitmap, new Matrix(), null);  
           // paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));  
            Bitmap pathBitmap = drawBitmapPath();  
            canvas.drawBitmap(pathBitmap,new Matrix(),null);  
            *//*Iterator<DrawPath> iter = savePath.iterator();  
            while (iter.hasNext()) {  
                DrawPath drawPath = iter.next();  
                canvas.drawPath(drawPath.path, drawPath.paint);  
            }*//*  
            //将合并后的bitmap保存为png图片到本地  
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);  
        }else {//没有背景图就画在一张白色为背景的bitmap上  
            *//*Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.RGB_565);  
            Canvas canvas = new Canvas(bitmap);  
            Paint paint = new Paint();  
            paint.setColor(Color.WHITE);  
            paint.setStyle(Paint.Style.FILL);  
            canvas.drawRect(0,0,screenWidth,screenHeight,paint);  
            Iterator<DrawPath> iter = savePath.iterator();  
            while (iter.hasNext()) {  
                DrawPath drawPath = iter.next();  
                canvas.drawPath(drawPath.path, drawPath.paint);  
            }*//*  
            mBitmap.compress(CompressFormat.PNG, 100, fos);  
        }  

但是在使用橡皮擦时出错误了,原因到现在理解的还是不是很透彻,可能是渲染模式只是覆盖的关系,但是橡皮擦仍会作为一种触摸痕迹也被保留了下来,所以发现使用橡皮擦后保存下来的图片不但没有擦掉原痕迹,连橡皮擦的痕迹也显示出来了,于是偷懒之下就想到了一个很便捷的方法:
我们只需要像截图一样把当前界面截取下来就行了,而且android也提供了view层的截取方法,步骤如下:

//view层的截图  
  view.setDrawingCacheEnabled(true);  
  Bitmap newBitmap = Bitmap.createBitmap(view.getDrawingCache());  
  viewt.setDrawingCacheEnabled(false);  

view表示你需要截取的控件,注意步骤一定要按照上面实现,那么只需要将截取的图片直接保存就可以了,于是在保存到sd卡的方法中修改

//保存到sd卡  
    public String saveToSDCard(Bitmap bitmap) {  
        //获得系统当前时间,并以该时间作为文件名  
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");  
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间  
        String str = formatter.format(curDate) + "paint.png";  
        String path= "sdcard/" + str;  
        File file = new File(path);  
        FileOutputStream fos = null;  
        try {  
            fos = new FileOutputStream(file);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        bitmap.compress(CompressFormat.PNG, 100, fos);  
        return path;  
    }  

另外要注意的是,图片要进行压缩,要不然连试几次就oom了:

 /** 
     * 通过uri获取图片并进行压缩 
     * 
     * @param uri 
     */  
    public Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {  
        InputStream input = ac.getContentResolver().openInputStream(uri);  
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();  
        onlyBoundsOptions.inJustDecodeBounds = true;  
        onlyBoundsOptions.inDither = true;//optional  
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional  
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);  
        input.close();  
        //图片宽高  
        int originalWidth = onlyBoundsOptions.outWidth;  
        int originalHeight = onlyBoundsOptions.outHeight;  
        if ((originalWidth == -1) || (originalHeight == -1))  
            return null;  
        //图片分辨率以480x800为标准  
        float hh = 800f;//这里设置高度为800f  
        float ww = 480f;//这里设置宽度为480f  
        //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
        int be = 1;//be=1表示不缩放  
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放  
            be = (int) (originalWidth / ww);  
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放  
            be = (int) (originalHeight / hh);  
        }  
        if (be <= 0)  
            be = 1;  
        //比例压缩  
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();  
        bitmapOptions.inSampleSize = be;//设置缩放比例  
        bitmapOptions.inDither = true;//optional  
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional  
        input = ac.getContentResolver().openInputStream(uri);  
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);  
        input.close();  
        return compressImageByQuality(bitmap);//再进行质量压缩  
    }  
    // 质量压缩方法  
    public Bitmap compressImageByQuality(Bitmap image) throws IOException {  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中  
        int options = 100;  
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩  
            baos.reset();//重置baos即清空baos  
            //第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差  ,第三个参数:保存压缩后的数据的流  
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中  
            options -= 10;//每次都减少10  
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
        isBm.close();  
        baos.close();  
        return bitmap;  
    }  

压缩方法网上资料很多,就不赘述了,需要注意的是我们需要根据所在画图控件的大小来调整图片宽高压缩比

以上基本上所有需要的东西已经全部做完了,以下就是锦上添花的功能:
例如:添加保存时的progressDialog以便好看一点:

public class CustomProgressDialog extends Dialog {  
    private Context context = null;  
    private static CustomProgressDialog customProgressDialog = null;  
    public CustomProgressDialog(Context context){  
        super(context);  
        this.context = context;  
    }  
    public CustomProgressDialog(Context context, int theme) {  
        super(context, theme);  
    }  
    public static CustomProgressDialog createDialog(Context context){  
        customProgressDialog = new CustomProgressDialog(context,R.style.CustomProgressDialog);  
        customProgressDialog.setContentView(R.layout.customprogressdialog);  
        return customProgressDialog;  
    }  
    public void onWindowFocusChanged(boolean hasFocus){  
        if (customProgressDialog == null){  
            return;  
        }  
        ImageView imageView = (ImageView) customProgressDialog.findViewById(R.id.loadingImageView);  
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getBackground();  
        animationDrawable.start();  
    }  
    public void setMessage(String strMessage){  
        TextView tvMsg = (TextView)customProgressDialog.findViewById(R.id.id_tv_loadingmsg);  
        if (tvMsg != null){  
            tvMsg.setText(strMessage);  
        }  
    }  
}  

progressDialog的xml文件:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:gravity="center"  
    android:orientation="vertical">  
    <ImageView  
        android:id="@+id/loadingImageView"  
        android:layout_width="30dp"  
        android:layout_height="30dp"  
        android:background="@drawable/progress_round"/>  
    <TextView  
        android:id="@+id/id_tv_loadingmsg"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="正在保存..."  
        android:textSize="16sp"  
        android:layout_marginTop="10dp"/>  
</LinearLayout>  

CustomProgressDialog 的样式:

<style name="CustomDialog" parent="@android:style/Theme.Dialog">  
        <item name="android:windowFrame">@null</item>  
        <item name="android:windowIsFloating">true</item>  
        <item name="android:windowContentOverlay">@null</item>  
        <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>  
        <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>  
    </style>  
    <style name="CustomProgressDialog" parent="@style/CustomDialog">  
        <item name="android:windowBackground">@android:color/transparent</item>  
        <item name="android:windowNoTitle">true</item>  
    </style>  

那么就只需要在保存时CustomProgressDialog.createDialog就行了,在ondestroy时dismiss即可

效果图:

6bee5d7d-8424-4d98-ab1b-3463f9da3c02.png

具体的源码就不贴出来了,没人喜欢看,要看的话可以在csdn上
自定义view实现涂鸦(画板)功能(二)

相关文章

网友评论

    本文标题:自定义view实现涂鸦(画板)功能(二)

    本文链接:https://www.haomeiwen.com/subject/cmtrjttx.html