Android: Change size of canvas / drawable in custo

2019-08-29 02:31发布

I'm trying to implement a custom drawable which should have the shape of a speechbubble. Therefore I use two paths, one draws the rect and the other should draw the triangle for the bubble.

My class looks like the following:

public class SpeechBubbleView extends Drawable {

private Paint mBubblePaint;
private Paint mBubblePaint2;

private Path mRectPath;

private Path mBubblePath;

public SpeechBubbleView() { }

public void initPaint() {
    mBubblePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mBubblePaint.setStyle(Paint.Style.FILL);
    mBubblePaint.setColor(Color.GREEN);

    mBubblePaint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
    mBubblePaint2.setStyle(Paint.Style.FILL);
    mBubblePaint2.setColor(Color.RED);

    int width = getBounds().width();
    int height = getBounds().height();

    mRectPath = new Path();
    mRectPath.addRoundRect(new RectF(0, 0, width, height), 8, 8, Path.Direction.CW);
    mRectPath.close();

    mBubblePath = new Path();
    mBubblePath.moveTo(50, height);
    mBubblePath.lineTo(100, height + 50);
    mBubblePath.lineTo(150, height);
    mBubblePath.close();
}

@Override
public void draw(Canvas canvas) {
    if(mRectPath == null && mPathValues == null) {
        initPaint();
    }

    canvas.drawPath(mRectPath, mBubblePaint);
    canvas.drawPath(mBubblePath, mBubblePaint2);
}

@Override
public void onBoundsChange(Rect bounds) {
    Rect customBound = new Rect(0, 0, bounds.width(), bounds.height() + 50);
    super.onBoundsChange(customBound);
}

The problem now is, that I take the width and height from the drawable to draw the rect of the speechbubble. The full space of the canvas is taken and there is no more room for the triangle to display below the rect.

My question now is: Is it possible to change the size of canvas or the drawable, so that I am able to display the small triangle below the rect?

I already tried the method onBoundsChange, but it takes no effect. In the draw-method the size is still the same. If possible, it would be nice to change the size directly in the custom drawable class, shown above, because I do not have the size of the view, when I call it. Also I cannot make the size of the rect smaller, because in the drawable there is content and if the rect is smaller, some of the content will be outside of the drawable. I use a drawable, so that I can simple call setBackgroundDrawable of my layout or TextView and it matches always the content size.

If anyone of you got an idea on how to do the size change, this would be very great. Thank you :D

0条回答
登录 后发表回答