android Xml画空心圆,Android - 绘画出圆并保存为图片

效果图

6cd25d3b7736

6cd25d3b7736

在相应路径下,生成1.png的照片

1. 添加权限

保存图片需要添加读写权限

Android 6.0 - 申请动态权限

2. 新建MyView类并继承View

public class MyView extends View {

public MyView(Context context) {

super(context);

}

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

Paint paint = new Paint();

/*

* Paint.Style.FILL设置只绘制图形内容

* Paint.Style.STROKE设置只绘制图形的边

* Paint.Style.FILL_AND_STROKE设置都绘制

* */

paint.setStyle(Paint.Style.FILL);

paint.setColor(Color.BLACK); //设置画笔颜色为:黑色

//paint.setStyle(Paint.Style.STROKE); //空心效果

//paint.setStrokeWidth((float) 3.0); //线宽

//paint.setAntiAlias(true); //设置抗锯齿

//paint.setStrokeWidth(7); //设置笔触宽度

/*

* public static Bitmap createBitmap(int width, int height, Config config)

* 参数一:宽

* 参数一:高

* 参数三: 图片格式

*          Bitmap.Config :https://blog.csdn.net/dalancon/article/details/7851143?utm_source=blogxgwz6

* */

Bitmap bitmap = Bitmap.createBitmap(700,700, Bitmap.Config.ARGB_8888);

//将图片指定区域,画到canvas的指定区域 (paint:一般填null)

//drawBitmap :https://blog.csdn.net/lovexieyuan520/article/details/50725539

canvas.drawBitmap(bitmap, 0, 0, null);

/*

* Canvas构造函数需要传入一个Bitmap,该bitmap是我们对canvas进行操作的载体,

* 比如:调用canvas的drawLine方法画一条线,将会把线画到bitmap里去。

* Canvas直接对该Bitmap对象进行修改,Bitmap保存我们的操作。

* */

canvas = new Canvas(bitmap);

canvas.drawColor(Color.WHITE); //设置为白色背景

/*

* public void drawCircle(float cx, float cy, float radius,Paint paint)

* 参数一:圆心的x坐标

* 参数二:圆心的y坐标

* 参数三:圆的半径

* 参数四:绘制时所使用的画笔

* */

canvas.drawCircle(150,150,100,paint); //绘制黑色圆

canvas.save(); //保存

canvas.restore(); // 存储

//存储地址

File file = new File("/storage/emulated/0/1/");

if(!file.exists()){

//如果不存在:根据File里的路径名建立文件夹

file.mkdirs();

}else {

try {

FileOutputStream fos = new FileOutputStream(file.getPath() + "/1.png");

//压缩图片 为百分之30

bitmap.compress(Bitmap.CompressFormat.PNG, 30, fos);

//清空缓冲区数据

fos.flush();

//关闭流

fos.close();

System.out.println("-------------save true------------");

} catch (Exception e) {

e.printStackTrace();

System.out.println("-------------save flase------------");

}

}

}

}

3. MainActivity.java

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

myView = new MyView(this);

FrameLayout frameLayout = findViewById(R.id.forever);

frameLayout.addView(myView);

}

----------------布局(activity_main.xml)---------------

android:layout_width="match_parent"

android:layout_height="match_parent"

android:id="@+id/forever"/>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值