我试图在 Android 中获取 2D 图形。 例如,我想实现一个自定义可绘制对象并将其显示在我的 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;
}
}
我正在尝试将其显示在我的 Activity 中,如下所示
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);
}
}
但是当我运行应用程序时,我在 Activity 上看不到矩形,有人可以帮我吗? 我哪里错了?
最佳答案
您的问题出在 getOpacity()
方法中。 100 不是有效值。你应该使用 PixelFormat值(value)。此外,您应该在构造函数中创建 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)
{
}
}
关于android - 在 Android 中实现自定义的可绘制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2967904/