Search code examples
androidscaleandroid-imageviewandroid-drawable

How to scale an own drawable in ImageView


i tried to add an own drawable object to an ImageView. i want that the drawable fits the ImageView. But if my resolution is to small the drawable is bigger than the ImageView.

Here my ImagaView:

<ScrollView 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"
>    
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
           ...
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="250dip"
                android:id="@+id/tvWeekStats"
                android:layout_below="@+id/llTimer"
                android:layout_margin="5dip"
                android:scaleType="fitXY"
                android:adjustViewBounds="true"
             />
      </RelativeLayout>
  </ScrollView>

And here is my drawable:

public class WeekdayDrawable extends Drawable {

private Paint paint;

public WeekdayDrawable() {
    this(new StatsWeekday());
}

public WeekdayDrawable(StatsWeekday ownTeam) {        
    paint = new Paint();
    paint.setStyle(Style.FILL);
}

@Override
public void draw(Canvas canvas) {
    try {
        canvas.save();

        paint.setColor(Color.WHITE);
        canvas.drawLine(0, 0, 700, 0, paint);
        canvas.drawLine(0, 10, 600, 10, paint);
        canvas.drawLine(0, 20, 500, 20, paint);
        canvas.drawLine(0, 30, 400, 30, paint);
        canvas.drawLine(0, 40, 300, 40, paint);

        canvas.drawRect(33, 60, 77, 77, paint );
        paint.setColor(Color.YELLOW);
        canvas.drawRect(33, 33, 77, 60, paint );            
        paint.setColor(Color.WHITE);
        paint.setTextSize(20);

        canvas.drawText("Some Text", 10, 25, paint);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void setAlpha(int alpha) {
    // Has no effect
}

@Override
public void setColorFilter(ColorFilter cf) {
    // Has no effect
}

@Override
public int getOpacity() {
    // Not Implemented
    return 0;
}

}

        Drawable weekStats;
        weekStats = new WeekdayDrawable(weekDayData);


        tvWeekStats.setImageDrawable(weekStats);

Thanks for any help


Solution

  • You shouldn't use static width and height like this canvas.drawLine(0, 0, 700, 0, paint);. Use Fractions of getHeight() and getWidth() instead, like:

    canvas.drawLine(0, 0, getHeight()/2, 0, paint);
    

    or so. Then the scalingproblem solves itself