2012-12-16 49 views
0

我動態地在自定義組件的繪製中添加一個位圖。android 9patched image無法伸展?

現在,當涉及到這一行:

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。

謝謝。

回答

1

你不應該在構造函數中做你的測量。在自定義視圖中,最好覆蓋onSizeChanged()。當視圖以當前的寬度和高度添加到視圖層次結構中時,將調用它,如果視圖的大小已重新調整,則會調用當前值和舊值。詳細信息請參見[Handle Layout Events]

+0

很酷的解決問題,我沒有寬度...但我忘了提及,它會拋出一個錯誤,當我想要設置的大小實際上比位圖大小...我應該放大圖片嗎? 9patch的東西不應該解決這個問題? –