引言
我们经常遇到需要在图片上进行编辑涂改的情况,电脑不能无时无刻带在我们身边,但是手机可以。
操作
在布局中设置两个部分,一个使用view存放需要涂改的图片,另一个用于安排清除涂鸦按钮和保存按钮。
图片部分:
com.example.myapplication2.HandWrite
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="300dp"
android:gravity="center_horizontal"/>
两个按钮部分:
<Button
android:id="@+id/clear"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="清除涂鸦"
/>
<Button
android:id="@+id/download"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="保存"
/>
编写涂鸦的画笔,确定画线的起始坐标和终点坐标,画笔颜色和宽度
Paint paint = null;
Bitmap originalBitmap = null;
Bitmap new1_Bitmap = null;
Bitmap new2_Bitmap = null;
float startX = 0,startY = 0;
float clickX = 0,clickY = 0;
boolean isMove = true;
boolean isClear = false;
int color = Color.BLUE;
float strokeWidth = 2f;
定义画笔操作和清除操作
public HandWrite(Context context, AttributeSet attrs)
{
super(context, attrs);
originalBitmap = BitmapFactory
.decodeResource(getResources(), R.drawable.dog)
.copy(Bitmap.Config.ARGB_8888,true);
new1_Bitmap = Bitmap.createBitmap(originalBitmap);
}
public void clear(){
isClear = true;
new2_Bitmap = Bitmap.createBitmap(originalBitmap);
invalidate();
}
public void setStyle(float strokeWidth){
this.strokeWidth = strokeWidth;
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawBitmap(HandWriting(new1_Bitmap), 0, 0,null);
}
public Bitmap HandWriting(Bitmap o_Bitmap)
{
Canvas canvas = null;
if(isClear) {
canvas = new Canvas(new2_Bitmap);
}
else{
canvas = new Canvas(o_Bitmap);
}
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setAntiAlias(true);
paint.setColor(color);
paint.setStrokeWidth(strokeWidth);
if(isMove)
{
canvas.drawLine(startX, startY, clickX, clickY, paint);
}
startX = clickX;
startY = clickY;
if(isClear)
{
return new2_Bitmap;
}
return o_Bitmap;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
clickX = event.getX();
clickY = event.getY();
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
isMove = false;
invalidate();
return true;
}
else if(event.getAction() == MotionEvent.ACTION_MOVE)
{
isMove = true;
invalidate();
return true;
}
return super.onTouchEvent(event);
}
对涂鸦后的图片进行保存。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn = (Button) findViewById(R.id.download);
}
public boolean saveBmpToPath(final Bitmap bitmap, final String filePath) {
if (bitmap == null || filePath == null) {
return false;
}
boolean result = false;
File file = new File(filePath);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
result = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close(); //关闭输出流
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
实现效果