简体   繁体   中英

draw a custom drawable without any size in Android

I'm trying to draw a drawable background with a path. But i getting to one point where i can't draw because i need the size of the object that will receive the background. Is there a function to find the size of the specific view that i will draw on ?

public class CustomDrawableEditText extends Drawable{
private Context context;
public CustomDrawableEditText(Context context) {
    // TODO Auto-generated constructor stub
    this.context = context;
}
@Override
public void draw(Canvas canvas) {
    // TODO Auto-generated method stub
    Path path = new Path();
    Paint paint = new Paint();
    path.moveTo(0, 0);
    path.lineTo(10, 0);
    path.moveTo(0, 0);
    path.lineTo(0, Y);
    path.lineTo(10,  Y);
    path.moveTo( X, 0);
    path.lineTo( X-10, 0);
    path.moveTo( X, 0);
    path.lineTo( X,  X);
    path.lineTo( X-10,  X);
    paint.setColor(context.getResources().getColor(R.color.orange));
    paint.setStrokeWidth(2);
    paint.setStyle(Paint.Style.STROKE);
    canvas.drawPath(path, paint);
}

private int getY() {
    final Resources res = context.getResources();
    final float scale = res.getDisplayMetrics().density;
    return (int) (res.getDimension(R.dimen.dim4) * scale + 0.5f);
}
@Override
public int getOpacity() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void setAlpha(int alpha) {
    // TODO Auto-generated method stub

}

@Override
public void setColorFilter(ColorFilter cf) {
    // TODO Auto-generated method stub

}

}

To get the size of a View you can invoke getWidth() and getHeight() . Note that you might be interested in getMeasuredWidth() and getMeasuredHeight() as well.

Make sure these methods are called after the layout process of your view.

Call the Drawable.getBounds() or Drawable.copyBounds(Rect rect) methods.

These two methods should return the View 's bounds (when a View 's size changes, it calls (should call) the Drawable.setBounds method on each Drawable it has with the appropriate parameter values) in which the View wants your Drawable to be drawn. Your own custom-Drawable can then retrieve this value by calling Drawable.getBounds() or Drawable.copyBounds(Rect rect) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM