android实现简单的画画板实例代码
直接看代码,注释都写清楚了
public class mainactivity extends activity {
private imageview iv;
private bitmap basebitmap;
private canvas canvas;
private paint paint;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
this.iv = (imageview) this.findviewbyid(r.id.iv);
// 创建一张空白图片
basebitmap = bitmap.createbitmap(480, 640, bitmap.config.argb_8888);
// 创建一张画布
canvas = new canvas(basebitmap);
// 画布背景为灰色
canvas.drawcolor(color.gray);
// 创建画笔
paint = new paint();
// 画笔颜色为红色
paint.setcolor(color.red);
// 宽度5个像素
paint.setstrokewidth(5);
// 先将灰色背景画上
canvas.drawbitmap(basebitmap, new matrix(), paint);
iv.setimagebitmap(basebitmap);
iv.setontouchlistener(new ontouchlistener() {
int startx;
int starty;
@override
public boolean ontouch(view v, motionevent event) {
switch (event.getaction()) {
case motionevent.action_down:
// 获取手按下时的坐标
startx = (int) event.getx();
starty = (int) event.gety();
break;
case motionevent.action_move:
// 获取手移动后的坐标
int stopx = (int) event.getx();
int stopy = (int) event.gety();
// 在开始和结束坐标间画一条线
canvas.drawline(startx, starty, stopx, stopy, paint);
// 实时更新开始坐标
startx = (int) event.getx();
starty = (int) event.gety();
iv.setimagebitmap(basebitmap);
break;
}
return true;
}
});
}
public void save(view view) {
try {
file file = new file(environment.getexternalstoragedirectory(),
system.currenttimemillis() + ".jpg");
outputstream stream = new fileoutputstream(file);
basebitmap.compress(compressformat.jpeg, 100, stream);
stream.close();
// 模拟一个广播,通知系统sdcard被挂载
intent intent = new intent();
intent.setaction(intent.action_media_mounted);
intent.setdata(uri.fromfile(environment
.getexternalstoragedirectory()));
sendbroadcast(intent);
toast.maketext(this, "保存图片成功", 0).show();
} catch (exception e) {
toast.maketext(this, "保存图片失败", 0).show();
e.printstacktrace();
}
}
}
简单的布局文件
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".mainactivity" >
<button
android:id="@+id/button1"
android:onclick="save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignparentbottom="true"
android:text="保存图片" />
<imageview
android:layout_above="@id/button1"
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</relativelayout>
再来个权限
<uses-permission android:name="android.permission.write_external_storage"/>
上两张我画的高端大气上档次的图片。。。。
推荐阅读
-
android实现简单的画画板实例代码
-
Android 使用fast-verification实现验证码填写功能的实例代码
-
PHP分页初探 一个最简单的PHP分页代码的简单实现_php实例
-
android 实现APP中改变头像图片的实例代码
-
实现JavaScript MVC样式框架的简单代码实例
-
Android listview ExpandableListView实现多选,单选,全选,edittext实现批量输入的实例代码
-
Android ContentProvider的实现及简单实例代码
-
Android studio 下JNI编程实例并生成so库的实现代码
-
Android实现常见的验证码输入框实例代码
-
android实现ViewPager的Indicator的实例代码