0

我想循环缩放我的图像视图。我的代码是

     final ImageView view1 = (ImageView) findViewById(R.id.test1);
    Thread timer = new Thread(){
        public void run(){
            long longTime = 100;
            long shortTime = 20;
            for (int x = 0; x < 2000000; x=x+10)
            {
                scaleImage( view1, i);
                try {
                    Thread.sleep(longTime);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    Thread.sleep(shortTime);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };

    timer.start();

尺度图像函数是

private void scaleImage(ImageView view, int boundBoxInDp)
{
    // Get the ImageView and its bitmap
    Drawable drawing = view.getDrawable();
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.zero);

    // Get current dimensions
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    float xScale = ((float) boundBoxInDp) / width;
    float yScale = ((float) boundBoxInDp) / height;
    float scale = (xScale <= yScale) ? xScale : yScale;
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the ImageView
    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    width = scaledBitmap.getWidth();
    height = scaledBitmap.getHeight();

    // Apply the scaled bitmap

    // Now change ImageView's dimensions to match the scaled image
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);
}

private int dpToPx(int dp)
{
    float density = getApplicationContext().getResources().getDisplayMetrics().density;
    return Math.round((float)dp * density);
}

但是当我在没有循环的情况下使用此代码时,我得到了异常,它只对一个函数调用工作正常,但在循环中的多个函数调用上它给了我异常,请帮助?

4

1 回答 1

1

尝试:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)       view.getLayoutParams();
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }
});
于 2013-10-31T08:00:47.857 回答