我正在尝试在RectShape中显示Text,它使用ShapeDrawable在Canvas中显示.
我能够在这段代码中显示RectShape,但是要查找如何在其上显示String!
public class CustomDrawableVIEw extends VIEw { private ShapeDrawable mDrawable; public CustomDrawableVIEw(Context context) { super(context); int x = 10; int y = 10; int wIDth = 300; int height = 50; mDrawable = new ShapeDrawable(new ovalShape()); mDrawable.getPaint().setcolor(0xff74AC23); mDrawable.setBounds(x, y, x + wIDth, y + height); } protected voID onDraw(Canvas canvas) { mDrawable.draw(canvas); } }
要么
public class ShapeDrawableTest extends VIEw { ShapeDrawable shapes = new ShapeDrawable(); public ShapeDrawableTest(Context context) { super(context); } public ShapeDrawableTest(Context context, AttributeSet attrs) { super(context, attrs); } @OverrIDe protected voID onDraw(Canvas canvas) { super.onDraw(canvas); shapes.draw(canvas); } @OverrIDe public boolean ontouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); // Use getX(int) for multi-finger // gestures int y = (int) event.getY(); makeShapeDrawable(x, y); invalIDate(); return (true); // Handled touch event } else { return (false); // DID not handle touch event } } private voID makeShapeDrawable(int x, int y) { int maxWIDth = getWIDth() / 10; int maxHeight = getHeight() / 10; Shape shape; shape = new RectShape(); shapes = new ShapeDrawable(shape); int wIDth = RandomUtils.randomInt(maxWIDth) + 5; int height = RandomUtils.randomInt(maxHeight) + 5; shapes.setBounds(x - wIDth / 2, y - height / 2, x + wIDth / 2, y + height / 2); shapes.getPaint().setcolor(color.BLUE); }}
我尝试的是:
public class CustomDrawableVIEw extends VIEw { public ShapeDrawable mDrawable; public CustomDrawableVIEw(Context context) { super(context); } public CustomDrawableVIEw(Context context, AttributeSet attrs) { super(context, attrs); int x = 10; int y = 10; int wIDth = 300; int height = 50; mDrawable = new ShapeDrawable(new ovalShape()); //mDrawable.getPaint().setcolor(0xff74AC23); final String s = "Hello"; Paint p = new Paint(); Rect bounds = new Rect(); bounds.set(x, y, x + wIDth, y + height); p.setTextSize(20); p.setcolor(color.YELLOW); p.getTextBounds(s, 0, s.length(), bounds); mDrawable.getPaint().getTextBounds(s, 0, s.length(), bounds); mDrawable.setBounds(x, y, x + wIDth, y + height); }// public CustomDrawableVIEw(Context context, AttributeSet attrs, int defStyle) {// super(context, attrs, defStyle);//// } public voID onDraw(Canvas canvas) { mDrawable.draw(canvas); } }
截图:
解决方法:
对我来说最好的选择是创建一个自定义TextDrawable,它可以正确处理如何显示一段文本.然后在onDraw(Canvas c)方法的CustomDrawableVIEw中,可以调用它来显示文本和椭圆.
看一下this answer I wrote recently,因为它包含了如何正确地完成它.
总结以上是内存溢出为你收集整理的如何在RectShape或OvalShape中使用Android Canvas ShapeDrawable显示文本?全部内容,希望文章能够帮你解决如何在RectShape或OvalShape中使用Android Canvas ShapeDrawable显示文本?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)