我尝试以编程方式创建一个ShapeDrawable,但以下代码没有显示任何内容。
ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
ShapeDrawable badge = new ShapeDrawable (new OvalShape());
badge.setBounds (0, 0, 200, 200);
badge.getPaint().setColor(Color.RED);
ImageView image = new ImageView (context);
image.setImageDrawable (badge);
addView (image);我可以让它与xml一起工作。
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="200px"
android:height="200px" />
<solid
android:color="#F00" />
</shape>
ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
image.setImageResource (R.drawable.badge);
addView (image);但我想以编程的方式创建它。xml可以完美地工作,所以问题不可能出在ImageView上,而一定是在创建ShapeDrawable时。
发布于 2016-01-07 09:07:07
使用setIntrinsicWidth和setIntrinsicHeight而不是setBounds来设置宽度和高度。
ImageView image = new ImageView (context);
image.setLayoutParams (new LayoutParams (200, 200));
ShapeDrawable badge = new ShapeDrawable (new OvalShape());
badge.setIntrinsicWidth (200);
badge.setIntrinsicHeight (200);
badge.getPaint().setColor(Color.RED);
image.setImageDrawable (badge);
addView (image);发布于 2016-01-07 04:47:36
您可能需要创建一个扩展ShapeDrawable的类来覆盖onDraw,然后创建类的一个实例。
示例:(完整示例的Source- check链接)
private static class MyShapeDrawable extends ShapeDrawable {
private Paint mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public MyShapeDrawable(Shape s) {
super(s);
mStrokePaint.setStyle(Paint.Style.STROKE);
}
public Paint getStrokePaint() {
return mStrokePaint;
}
@Override protected void onDraw(Shape s, Canvas c, Paint p) {
s.draw(c, p);
s.draw(c, mStrokePaint);
}
}https://stackoverflow.com/questions/34642224
复制相似问题