最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

在图片上涂鸦(其实就是乱画 O(∩

IT培训 admin 0浏览 0评论

在图片上涂鸦(其实就是乱画 O(∩

帮一个小孩解决图片涂鸦的问题,问题解决完了,来记录一下,以后用的时候直接Copy

  1. 定义个view继承ImageView 
    package com.example.help;import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.PaintFlagsDrawFilter;
    import android.graphics.Path;
    import android.graphics.PorterDuff;
    import android.util.AttributeSet;
    import android.view.MotionEvent;import androidx.appcompat.widget.AppCompatImageView;public class MyImageview extends AppCompatImageView {private Path mPath;//绘制路径private Paint mPaint;// 绘制画笔private Canvas mCanvas;//背景画布private Bitmap mMBitmap;//背景bitmappublic MyImageview(Context context) {this(context, null);}public MyImageview(Context context, AttributeSet attrs) {this(context, attrs, 0);}public MyImageview(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);initPaint();}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);}@Overrideprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {super.onLayout(changed, left, top, right, bottom);mMBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);mCanvas = new Canvas(mMBitmap);mCanvas.drawColor(Color.TRANSPARENT);mCanvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));}private void initPaint() {mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);mPaint.setColor(Color.BLACK);mPaint.setStrokeWidth(10.0f);mPaint.setStrokeCap(Paint.Cap.ROUND);mPaint.setStyle(Paint.Style.STROKE);mPaint.setStrokeJoin(Paint.Join.ROUND);mPaint.setDither(true);mPath = new Path();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));canvas.drawBitmap(mMBitmap, 0, 0, mPaint);// 通过画布绘制多点形成的图形canvas.drawPath(mPath, mPaint);}private float[] downPoint = new float[2];private float[] previousPoint = new float[2];@Overridepublic boolean onTouchEvent(MotionEvent event) {downPoint[0] = event.getX();downPoint[1] = event.getY();switch (event.getAction()) {case MotionEvent.ACTION_DOWN:previousPoint[0] = downPoint[0];previousPoint[1] = downPoint[1];mPath.moveTo(downPoint[0], downPoint[1]);break;case MotionEvent.ACTION_MOVE:float dX = Math.abs(downPoint[0] - previousPoint[0]);float dY = Math.abs(downPoint[1] - previousPoint[1]);// 两点之间的距离大于等于3时,生成贝塞尔绘制曲线if (dX >= 3 || dY >= 3) {// 设置贝塞尔曲线的操作点为起点和终点的一半float cX = (downPoint[0] + previousPoint[0]) / 2;float cY = (downPoint[1] + previousPoint[1]) / 2;// 二次贝塞尔,实现平滑曲线;previousX, previousY为操作点,cX, cY为终点mPath.quadTo(previousPoint[0], previousPoint[1], cX, cY);// 第二次执行时,第一次结束调用的坐标值将作为第二次调用的初始坐标值previousPoint[0] = downPoint[0];previousPoint[1] = downPoint[1];}break;case MotionEvent.ACTION_UP:mCanvas.drawPath(mPath, mPaint);mPath.reset();break;}invalidate();return true;}public void clear() {if (mCanvas != null) {mPath.reset();mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);invalidate();}}}

     

  2. 引用
        /*** 主要方法:创建一个bitmap放于画布之上进行绘制*/private static Bitmap convertViewToBitmap(View tempView) {Bitmap bitmap = Bitmap.createBitmap(tempView.getWidth(),tempView.getHeight(), Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(bitmap);tempView.draw(canvas);return bitmap;}

    友情提示:设置图片可以用glide,convertViewToBitmap方法拿到bitmap后自行处理(保存到本地或者上传啥的)


今天无聊,更新一下这个,加上保存到本地,在保存之前要动态申请读写权限(针对6.0以上),直接上代码了

package com.example.help2;import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;public class MainActivity extends AppCompatActivity {private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE};int[] res = new int[]{R.drawable.icon_address, R.drawable.icon_shoucang, R.drawable.icon_weishoucang};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final MyImageview imageview = findViewById(R.id.image);imageview.setImageResource(R.drawable.icon_address);final ImageView imageView2 = findViewById(R.id.image2);checkPermission();findViewById(R.id.commit).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Bitmap bitmap = convertViewToBitmap(imageview);imageView2.setImageBitmap(bitmap);saveImageToGallery(bitmap);imageview.clear();imageview.setImageResource(res[new Random().nextInt(2)]);}});}/*** 主要方法:创建一个bitmap放于画布之上进行绘制*/private static Bitmap convertViewToBitmap(View tempView) {Bitmap bitmap = Bitmap.createBitmap(tempView.getWidth(),tempView.getHeight(), Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(bitmap);tempView.draw(canvas);return bitmap;}/*** 保存图片到本地* @param bmp* @return*/public int saveImageToGallery(Bitmap bmp) {//生成路径String root = Environment.getExternalStorageDirectory().getAbsolutePath();String dirName = "dou";File appDir = new File(root , dirName);if (!appDir.exists()) {appDir.mkdirs();}//文件名为时间long timeStamp = System.currentTimeMillis();SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String sd = sdf.format(new Date(timeStamp));String fileName = sd + ".jpg";//获取文件File file = new File(appDir, fileName);FileOutputStream fos = null;try {fos = new FileOutputStream(file);bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);fos.flush();//通知系统相册刷新MainActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(new File(file.getPath()))));return 2;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fos != null) {fos.close();}} catch (IOException e) {e.printStackTrace();}}return -1;}/*** 检查权限*/public void checkPermission() {if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 100);}}}@Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);if (requestCode == 1) {for (int i = 0; i < permissions.length; i++) {Log.d("MainActivity", "申请的权限为:" + permissions[i] + ",申请结果:" + grantResults[i]);}}}
}

 

在图片上涂鸦(其实就是乱画 O(∩

帮一个小孩解决图片涂鸦的问题,问题解决完了,来记录一下,以后用的时候直接Copy

  1. 定义个view继承ImageView 
    package com.example.help;import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.PaintFlagsDrawFilter;
    import android.graphics.Path;
    import android.graphics.PorterDuff;
    import android.util.AttributeSet;
    import android.view.MotionEvent;import androidx.appcompat.widget.AppCompatImageView;public class MyImageview extends AppCompatImageView {private Path mPath;//绘制路径private Paint mPaint;// 绘制画笔private Canvas mCanvas;//背景画布private Bitmap mMBitmap;//背景bitmappublic MyImageview(Context context) {this(context, null);}public MyImageview(Context context, AttributeSet attrs) {this(context, attrs, 0);}public MyImageview(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);initPaint();}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);}@Overrideprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {super.onLayout(changed, left, top, right, bottom);mMBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);mCanvas = new Canvas(mMBitmap);mCanvas.drawColor(Color.TRANSPARENT);mCanvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));}private void initPaint() {mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);mPaint.setColor(Color.BLACK);mPaint.setStrokeWidth(10.0f);mPaint.setStrokeCap(Paint.Cap.ROUND);mPaint.setStyle(Paint.Style.STROKE);mPaint.setStrokeJoin(Paint.Join.ROUND);mPaint.setDither(true);mPath = new Path();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));canvas.drawBitmap(mMBitmap, 0, 0, mPaint);// 通过画布绘制多点形成的图形canvas.drawPath(mPath, mPaint);}private float[] downPoint = new float[2];private float[] previousPoint = new float[2];@Overridepublic boolean onTouchEvent(MotionEvent event) {downPoint[0] = event.getX();downPoint[1] = event.getY();switch (event.getAction()) {case MotionEvent.ACTION_DOWN:previousPoint[0] = downPoint[0];previousPoint[1] = downPoint[1];mPath.moveTo(downPoint[0], downPoint[1]);break;case MotionEvent.ACTION_MOVE:float dX = Math.abs(downPoint[0] - previousPoint[0]);float dY = Math.abs(downPoint[1] - previousPoint[1]);// 两点之间的距离大于等于3时,生成贝塞尔绘制曲线if (dX >= 3 || dY >= 3) {// 设置贝塞尔曲线的操作点为起点和终点的一半float cX = (downPoint[0] + previousPoint[0]) / 2;float cY = (downPoint[1] + previousPoint[1]) / 2;// 二次贝塞尔,实现平滑曲线;previousX, previousY为操作点,cX, cY为终点mPath.quadTo(previousPoint[0], previousPoint[1], cX, cY);// 第二次执行时,第一次结束调用的坐标值将作为第二次调用的初始坐标值previousPoint[0] = downPoint[0];previousPoint[1] = downPoint[1];}break;case MotionEvent.ACTION_UP:mCanvas.drawPath(mPath, mPaint);mPath.reset();break;}invalidate();return true;}public void clear() {if (mCanvas != null) {mPath.reset();mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);invalidate();}}}

     

  2. 引用
        /*** 主要方法:创建一个bitmap放于画布之上进行绘制*/private static Bitmap convertViewToBitmap(View tempView) {Bitmap bitmap = Bitmap.createBitmap(tempView.getWidth(),tempView.getHeight(), Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(bitmap);tempView.draw(canvas);return bitmap;}

    友情提示:设置图片可以用glide,convertViewToBitmap方法拿到bitmap后自行处理(保存到本地或者上传啥的)


今天无聊,更新一下这个,加上保存到本地,在保存之前要动态申请读写权限(针对6.0以上),直接上代码了

package com.example.help2;import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;public class MainActivity extends AppCompatActivity {private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE};int[] res = new int[]{R.drawable.icon_address, R.drawable.icon_shoucang, R.drawable.icon_weishoucang};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final MyImageview imageview = findViewById(R.id.image);imageview.setImageResource(R.drawable.icon_address);final ImageView imageView2 = findViewById(R.id.image2);checkPermission();findViewById(R.id.commit).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Bitmap bitmap = convertViewToBitmap(imageview);imageView2.setImageBitmap(bitmap);saveImageToGallery(bitmap);imageview.clear();imageview.setImageResource(res[new Random().nextInt(2)]);}});}/*** 主要方法:创建一个bitmap放于画布之上进行绘制*/private static Bitmap convertViewToBitmap(View tempView) {Bitmap bitmap = Bitmap.createBitmap(tempView.getWidth(),tempView.getHeight(), Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(bitmap);tempView.draw(canvas);return bitmap;}/*** 保存图片到本地* @param bmp* @return*/public int saveImageToGallery(Bitmap bmp) {//生成路径String root = Environment.getExternalStorageDirectory().getAbsolutePath();String dirName = "dou";File appDir = new File(root , dirName);if (!appDir.exists()) {appDir.mkdirs();}//文件名为时间long timeStamp = System.currentTimeMillis();SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String sd = sdf.format(new Date(timeStamp));String fileName = sd + ".jpg";//获取文件File file = new File(appDir, fileName);FileOutputStream fos = null;try {fos = new FileOutputStream(file);bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);fos.flush();//通知系统相册刷新MainActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(new File(file.getPath()))));return 2;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fos != null) {fos.close();}} catch (IOException e) {e.printStackTrace();}}return -1;}/*** 检查权限*/public void checkPermission() {if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 100);}}}@Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);if (requestCode == 1) {for (int i = 0; i < permissions.length; i++) {Log.d("MainActivity", "申请的权限为:" + permissions[i] + ",申请结果:" + grantResults[i]);}}}
}

 

发布评论

评论列表 (0)

  1. 暂无评论