永发信息网

怎么用Android画一个正方形

答案:2  悬赏:30  手机版
解决时间 2021-12-28 13:52
  • 提问者网友:ミ烙印ゝ
  • 2021-12-27 17:25
怎么用Android画一个正方形
最佳答案
  • 五星知识达人网友:雾月
  • 2021-12-27 19:04
先来介绍一下画几何图形要用到的,画布(Canvas)、画笔(Paint)。
1. 画一个圆使用的是drawCircle:canvas.drawCircle(cx, cy, radius, paint);x、y代表坐标、radius是半径、paint是画笔,就是画图的颜色;
2. 在画图的时候还要有注意,你所画的矩形是实心(paint.setStyle(Paint.Style.FILL))还是空心(paint.setStyle(Paint.Style.STROKE);
画图的时候还有一点,那就是消除锯齿:paint.setAntiAlias(true);
3. 还有就是设置一种渐变颜色的矩形:
Shader mShader = new LinearGradient(0,0,100,100, new int[]{Color.RED,Color.GREEn,Color.BLUE,Color.YELLO},null,Shader.TileMode.REPEAT);
ShapeDrawable sd;
//画一个实心正方形
sd = new ShapeDrawable(new RectShape());
sd.setBounds(20,20,100,100);
sd.draw(canvas);
//一个渐变色的正方形就完成了

4. 正方形:drawRect:canvas.drawRect(left, top, right, bottom, paint)
这里的left、top、right、bottom的值是:
left:是矩形距离左边的X轴
top:是矩形距离上边的Y轴
right:是矩形距离右边的X轴
bottom:是矩形距离下边的Y轴
5. 长方形:他和正方形是一个原理,这个就不用说了
6. 椭圆形:记住,这里的Rectf是float类型的
RectF re = new Rect(left, top, right, bottom);
canvas.drawOval(re,paint);

好了,说了这么多的的东西,那就让我们来看一下真正的实例吧!!!
package com.hades.game;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
public class CanvasActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyView myView = new MyView(this);
setContentView(myView);
}
public class MyView extends View {
public MyView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 设置画布的背景颜色
canvas.drawColor(Color.WHITE);

// 定义画笔1
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
// 消除锯齿
paint.setAntiAlias(true);
// 设置画笔的颜色
paint.setColor(Color.RED);
// 设置paint的外框宽度
paint.setStrokeWidth(2);
// 画一个圆
canvas.drawCircle(40, 30, 20, paint);
// 画一个正放形
canvas.drawRect(20, 70, 70, 120, paint);
// 画一个长方形
canvas.drawRect(20, 170, 90, 130, paint);
// 画一个椭圆
RectF re = new RectF(20, 230, 100, 190);
canvas.drawOval(re, paint);

paint.setStyle(Paint.Style.FILL);
// 定义画笔2
Paint paint2 = new Paint();
// 消除锯齿
paint2.setAntiAlias(true);
// 设置画笔的颜色
paint2.setColor(Color.BLUE);
// 画一个空心圆
canvas.drawCircle(150, 30, 20, paint2);
// 画一个正方形
canvas.drawRect(185, 70, 130, 120, paint2);
// 画一个长方形
canvas.drawRect(200, 130, 130, 180, paint2);
// 画一个椭圆形
RectF re2 = new RectF(200, 230, 130, 190);
canvas.drawOval(re2, paint2);
}
}
}
全部回答
  • 1楼网友:夜风逐马
  • 2021-12-27 19:59
画圆角矩形 建立 rect_gray.xml文件放在drawable文件夹下面。 然后在布局的xml里面: 作为imageview或者linearlayout等作为背景源就可以了。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯