我试图在Android中掌握2D图形。 作为一个例子,我想实现一个自定义drawable并在我的Activity
中显示它我已经通过扩展Android drawable来定义一个自定义的drawable,如下所述
class myDrawable extends Drawable {
private static final String TAG = myDrawable.class.getSimpleName();
private ColorFilter cf;
@Override
public void draw(Canvas canvas) {
//First you define a colour for the outline of your rectangle
Paint rectanglePaint = new Paint();
rectanglePaint.setARGB(255, 255, 0, 0);
rectanglePaint.setStrokeWidth(2);
rectanglePaint.setStyle(Style.FILL);
//Then create yourself a Rectangle
RectF rectangle = new RectF(15.0f, 50.0f, 55.0f, 75.0f); //in pixels
Log.d(TAG,"On Draw method");
// TODO Auto-generated method stub
Paint paintHandl = new Paint();
// paintHandl.setColor(0xaabbcc);
paintHandl.setARGB(125, 234, 213, 34 );
RectF rectObj = new RectF(5,5,25,25);
canvas.drawRoundRect(rectangle, 0.5f, 0.5f, rectanglePaint);
}
@Override
public int getOpacity() {
// TODO Auto-generated method stub
return 100;
}
@Override
public void setAlpha(int alpha) {
// TODO Auto-generated method stub
}
@Override
public void setColorFilter(ColorFilter cf) {
// TODO Auto-generated method stub
this.cf = cf;
}
}
我想在我的活动中显示这个,如下所示
public class custDrawable extends Activity {
/** Called when the activity is first created. */
LinearLayout layObj = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layObj = (LinearLayout) findViewById(R.id.parentLay);
ImageView imageView = (ImageView) findViewById(R.id.icon2);
myDrawable myDrawObj = new myDrawable();
imageView.setImageDrawable(myDrawObj);
imageView.invalidate();
// layObj.addView(myDrawObj, params);
}
}
但是当我运行应用程序时,我看到活动上没有矩形,有人可以帮助我吗? 我哪里错了?
答案 0 :(得分:12)
您的问题出在getOpacity()
方法中。 100不是有效值。您应该使用PixelFormat值。此外,您应该在构造函数中创建RectF
和Paint
,然后只调整draw()
中的值,这样就不会创建那么多需要垃圾回收的对象。像这样:
public class Square extends Drawable
{
private final Paint mPaint;
private final RectF mRect;
public Square()
{
mPaint = new Paint();
mRect = new RectF();
}
@Override
public void draw(Canvas canvas)
{
// Set the correct values in the Paint
mPaint.setARGB(255, 255, 0, 0);
mPaint.setStrokeWidth(2);
mPaint.setStyle(Style.FILL);
// Adjust the rect
mRect.left = 15.0f;
mRect.top = 50.0f;
mRect.right = 55.0f;
mRect.bottom = 75.0f;
// Draw it
canvas.drawRoundRect(mRect, 0.5f, 0.5f, mPaint);
}
@Override
public int getOpacity()
{
return PixelFormat.OPAQUE;
}
@Override
public void setAlpha(int arg0)
{
}
@Override
public void setColorFilter(ColorFilter arg0)
{
}
}
答案 1 :(得分:0)
您可能必须实现其他覆盖,例如getIntrinsicWidth()和getIntrinsicHeight()。一种方法是将layout_width和layout_height设置为某个常量(layout_width =" 42dip" layout_height =" 42dip"在XML中或如果您使用Java将layoutParams设置为某个值布局)。有些View类型处理没有getIntrinsic *实现,所以试试吧!这包括直观视图
如果没有特定的宽度或高度,您可以尝试返回-1。
很难说这个问题是否得到了解决,但我是通过Google来到这里试图帮助自己记住制作自定义Drawable的细节,而且我想帮助人们避免这个问题:http://xkcd.com/979/