0

我在自定义组件的绘制上动态添加位图。

现在谈到这一行:

    line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);

我想将位图拉伸到组件的宽度。我在这里使用line.getWidth(),但我希望有一种说法this.getWidth。不幸的是,它在构造函数中,视图仍然不知道它的宽度。

这是自定义组件的代码:

package com.adylitica.components;

import com.adylitica.activity.R;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Defines a custom EditText View that draws lines between each line of text that is displayed.
 */
public class EditTextNotes extends EditText {

private Rect mRect;
private Bitmap line;
public static int nbLines = 0;
private SharedPreferences settings;


public EditTextNotes(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    line = BitmapFactory.decodeResource(context.getResources(), R.drawable.line_thin_new);
    line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);

    mRect = new Rect();
}

public EditTextNotes(Context context, AttributeSet attrs) {
    super(context, attrs);

    line = BitmapFactory.decodeResource(context.getResources(), R.drawable.line_thin_new);
    line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);

    mRect = new Rect();

}

public EditTextNotes(Context context) {
    super(context);

    line = BitmapFactory.decodeResource(context.getResources(), R.drawable.line_thin_new);
    line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);

    mRect = new Rect();
}


@Override
protected void onDraw(Canvas canvas) {

    int count = getLineCount();

    Rect r = mRect;

    int baseline = 0;
    int addSize = 0;
    canvas.drawBitmap(line, 0, baseline, null);

    for (int i = 0; i < count; i++) {
        baseline = getLineBounds(i, r) + addSize;
        canvas.drawBitmap(line, 0, baseline, null);
        nbLines++;
    }

    super.onDraw(canvas);
}

}

PS:位图是9patched。

谢谢。

4

1 回答 1

1

您不应该在构造函数中进行测量。在自定义视图中,最好覆盖onSizeChanged(). 当您的视图被添加到具有当前宽度和高度的视图层次结构中时,它将被调用,如果您的视图被调整大小,则再次使用当前值和旧值。有关详细信息,请参阅[处理布局事件]

于 2012-12-16T06:04:37.657 回答