用Android studio写构建一个画板的文件。包括以下功能:1、修改描边宽度;2、更改画板颜色;3、擦除;4、全部清除;5、保存;6、退出。
时间: 2023-06-20 09:04:06 浏览: 111
android实现画板功能
5星 · 资源好评率100%
以下是一个简单的画板应用程序的代码。包括所需的功能:修改描边宽度、更改画板颜色、擦除、全部清除、保存、退出。
MainActivity.java:
```java
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private DrawingView drawingView;
private SeekBar seekBar;
private Button clearBtn, eraseBtn, saveBtn, exitBtn;
private int strokeWidth = 4;
private int currentColor = Color.BLACK;
private boolean eraseMode = false;
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawingView = new DrawingView(this);
LinearLayout layout = findViewById(R.id.layout);
layout.addView(drawingView);
seekBar = findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
strokeWidth = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
clearBtn = findViewById(R.id.clearBtn);
clearBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawingView.clear();
}
});
eraseBtn = findViewById(R.id.eraseBtn);
eraseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
eraseMode = !eraseMode;
if (eraseMode) {
eraseBtn.setText(R.string.draw_mode);
} else {
eraseBtn.setText(R.string.erase_mode);
}
}
});
saveBtn = findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE);
} else {
saveImage();
}
}
});
exitBtn = findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void saveImage() {
String fileName = UUID.randomUUID().toString() + ".png";
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
Bitmap bitmap = drawingView.getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(this, R.string.image_saved, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, R.string.image_save_error, Toast.LENGTH_SHORT).show();
}
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
saveImage();
} else {
Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public class DrawingView extends View {
private Bitmap bitmap;
private Canvas canvas;
private Path path;
private Paint paint;
public DrawingView(Context context) {
super(context);
bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
path = new Path();
paint = new Paint();
paint.setColor(currentColor);
paint.setStrokeWidth(strokeWidth);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
setDrawingCacheEnabled(true);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bitmap, 0, 0, null);
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(x, y);
break;
case MotionEvent.ACTION_MOVE:
path.lineTo(x, y);
break;
case MotionEvent.ACTION_UP:
canvas.drawPath(path, paint);
path.reset();
break;
default:
return false;
}
invalidate();
return true;
}
public void clear() {
canvas.drawColor(Color.WHITE);
invalidate();
}
public Bitmap getBitmap() {
return getDrawingCache();
}
public void setColor(int color) {
currentColor = color;
paint.setColor(currentColor);
}
public void setStrokeWidth(int width) {
strokeWidth = width;
paint.setStrokeWidth(strokeWidth);
}
public void setEraseMode(boolean erase) {
eraseMode = erase;
if (erase) {
paint.setColor(Color.WHITE);
} else {
paint.setColor(currentColor);
}
}
}
}
```
activity_main.xml:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="20"
android:progress="4"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/clearBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/clear"/>
<Button
android:id="@+id/eraseBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/erase_mode"/>
<Button
android:id="@+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save"/>
<Button
android:id="@+id/exitBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/exit"/>
</LinearLayout>
</LinearLayout>
```
strings.xml:
```xml
<resources>
<string name="app_name">My Drawing Board</string>
<string name="clear">Clear</string>
<string name="erase_mode">Erase Mode</string>
<string name="draw_mode">Draw Mode</string>
<string name="save">Save</string>
<string name="exit">Exit</string>
<string name="image_saved">Image saved successfully.</string>
<string name="image_save_error">Error while saving image.</string>
<string name="permission_denied">Permission denied.</string>
</resources>
```
在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
阅读全文