关于Android教程的问题

时间:2013-05-15 15:17:54

标签: android bitmap drawable

我开始在Android中学习位图和简单图形。我对此有点新意,所以我仍然试图掌握这些概念。我的代码来自教程。它适用于位图和drawable。我得到它来显示三角形的图像。但我有几个问题:第一:三角形的图像显示 - 但它的基础延伸到屏幕的底部。我该如何解决?第二:如何在屏幕中央显示三角形?

我的代码(摘自vogella.com):

drawable的类:

public class MyRoundCornerDrawable extends Drawable {

private Paint paint;

public MyRoundCornerDrawable(Bitmap bitmap){
    BitmapShader shader;
    shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
            Shader.TileMode.CLAMP);
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(shader);
}

@Override
public void draw(Canvas canvas) {
    int height = getBounds().height();
    int width = getBounds().width();
     RectF rect = new RectF(0.0f, 0.0f, width, height);
        canvas.drawRoundRect(rect, 15, 15, paint);

}

@Override
public int getOpacity() {

    return 255;
}

@Override
public void setAlpha(int alpha) {


}

@Override
public void setColorFilter(ColorFilter arg0) {


}

}

MainActivity

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView button = (ImageView) findViewById(R.id.image);
    InputStream resource = getResources().openRawResource(R.drawable.triangle);
    Bitmap bitmap = BitmapFactory.decodeStream(resource);
    button.setBackground(new MyRoundCornerDrawable(bitmap));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

和XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

 <ImageView
     android:id="@+id/image"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:contentDescription="TODO" />

1 个答案:

答案 0 :(得分:0)

  1. scaleType添加ImageViewfitXYcenter可以解决问题
  2. layout_centerInParent="true"添加到您的ImageView

    <ImageView
        android:scaleType="center"
        android:id="@+id/image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        layout_centerInParent="true" 
        android:contentDescription="TODO" />