Kar*_*ick 32 android canvas drawable
我正在尝试为android开发一个简单的饼图类.现在,它可以获取标签和值的映射并绘制饼图.我还没有添加馅饼的图例,这是我需要将文本放在屏幕角落的小矩形附近的地方.任何帮助表示赞赏,因为我是Android开发人员的新手.
Jea*_*oin 51
您将不得不使用Canvas类的drawText方法.
Paint paint = new Paint();
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(16);
canvas.drawText("My Text", x, y, paint);
Run Code Online (Sandbox Code Playgroud)
这是关于它的相关文档:
这里曾经有另一个答案被删除,因为它只是一个链接.原始链接在这里.代码基本相同,但我拿出了非文本绘图部分,并且还扩大了尺寸,以便在现代屏幕密度上更好地工作.
这只是展示了一些你可以用文字绘制做的事情.
这是更新的代码:
public class MainActivity extends AppCompatActivity {
DemoView demoview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demoview = new DemoView(this);
setContentView(demoview);
}
private class DemoView extends View {
public DemoView(Context context){
super(context);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// custom drawing code here
// remember: y increases from top to bottom
// x increases from left to right
int x = 0;
int y = 0;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
canvas.save();
canvas.translate(100, 200);
// make the entire canvas white
canvas.drawColor(Color.WHITE);
// draw some text using STROKE style
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
paint.setColor(Color.MAGENTA);
paint.setTextSize(100);
canvas.drawText("Style.STROKE", 0, 0, paint);
canvas.translate(0, 200);
// draw some text using FILL style
paint.setStyle(Paint.Style.FILL);
//turn antialiasing on
paint.setAntiAlias(true);
//paint.setTextSize(30);
canvas.drawText("Style.FILL", 0, 0, paint);
canvas.translate(0, 200);
// draw some rotated text
// get text width and height
// set desired drawing location
x = 75;
y = 185;
paint.setColor(Color.GRAY);
//paint.setTextSize(25);
String str2rotate = "Rotated!";
// draw bounding rect before rotating text
Rect rect = new Rect();
paint.getTextBounds(str2rotate, 0, str2rotate.length(), rect);
canvas.translate(x, y);
paint.setStyle(Paint.Style.FILL);
// draw unrotated text
canvas.drawText("!Rotated", 0, 0, paint);
paint.setStyle(Paint.Style.STROKE);
canvas.drawRect(rect, paint);
// undo the translate
canvas.translate(-x, -y);
// rotate the canvas on center of the text to draw
canvas.rotate(-45, x + rect.exactCenterX(),
y + rect.exactCenterY());
// draw the rotated text
paint.setStyle(Paint.Style.FILL);
canvas.drawText(str2rotate, x, y, paint);
//undo the translation and rotation
canvas.restore();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想稍后尝试的其他东西是沿着路径绘制文本.
另请参阅此处更全面的答案,其中给出了以下图像.
| 归档时间: |
|
| 查看次数: |
72437 次 |
| 最近记录: |