首页 文章

在SomeView类onDrawBitmap方法中将位图拟合到屏幕

提问于
浏览
0

首先,它不仅仅是将位图缩放到所有屏幕 . 这不重复 . 我搜索了它 .

我有一个名为SomeView的类,我在 MainActivity 上调用 SomeView class ;

setContentView(new SomeView(MainActivity.this, bitmap ));

来自 MainActivity. 的Sendind位图

我正在使用加载图像

canvas.drawBitmap(bitmap, 0, 0, null);

我也试过了 .

RectF dest = new RectF(0,0,getWidth(),getHeight());
  canvas.drawBitmap(bitmap, null, dest, null);

并试过..

RectF dest = new RectF(0,0,bitmap.getWidth(),bitmap.getHeight());
      canvas.drawBitmap(bitmap, null, dest, null);

但没有什么对我有用...即将到来的位图不适合屏幕而不适合中心 .

What I have..

What I need.

我的查看活动代码 . SomeView.Java

public SomeView(Context c, Bitmap b) {
        super(c);

        bitmap = b;
        mContext = c;
        setFocusable(true);
        setFocusableInTouchMode(true);

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setPathEffect(new DashPathEffect(new float[] { 10, 20 }, 0));
        paint.setStrokeWidth(15);
        paint.setColor(Color.GREEN);


        this.setOnTouchListener(this);
        points = new ArrayList<Point>();

        bfirstpoint = false;
    }

    public SomeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setFocusable(true);
        setFocusableInTouchMode(true);

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setColor(Color.WHITE);

        this.setOnTouchListener(this);
        points = new ArrayList<Point>();
        bfirstpoint = false;

    }

    public void onDraw(Canvas canvas) {

        canvas.drawBitmap(bitmap, 0, 0, null);

        Path path = new Path();
        boolean first = true;

        for (int i = 0; i < points.size(); i += 2) {
            Point point = points.get(i);
            if (first) {
                first = false;
                path.moveTo(point.x, point.y);
            } else if (i < points.size() - 1) {
                Point next = points.get(i + 1);
                path.quadTo(point.x, point.y, next.x, next.y);
            } else {
                mlastpoint = points.get(i);
                path.lineTo(point.x, point.y);
            }
        }
        canvas.drawPath(path, paint);
    }

1 回答

  • 1

    这是解决方案 .

    RectF src = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
    RectF dst = new RectF(0, 0, getWidth(), getHeight());
    
    matrix = new Matrix();
    matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
    
    Log.d(TAG, "MATRIX VALUE: " + matrix);
    
    canvas.drawBitmap(bitmap, matrix, null);
    

相关问题