android截屏并将截图缩放

package com.ych.demo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
/**
 * 此demo实现了截屏并将截图放到指定的控件上缩放显示
 * 技术要点:
 * 1.截屏
 * 2.缩放功能
 * @author: 严程
 * @CreateDate: 2012-08-09
 */
public class Demo4Activity extends Activity {
	private Button but;
	private ImageButton img;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        but = (Button)findViewById(R.id.but);
        but.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 实现截屏
				View view = Demo4Activity.this.getWindow().getDecorView();
				// 启动缓存
				view.setDrawingCacheEnabled(true);
				// 接收数据
				Bitmap bitmap = view.getDrawingCache();
				img.setImageBitmap(zoomBitmap(bitmap));
				
			}
		});
        img = (ImageButton)findViewById(R.id.img);
        img.setBackgroundColor(Color.RED);
    }

    /**
     * 实现图缩放
     * @param target
     * @return
     */
    public Bitmap zoomBitmap(Bitmap target){
    	// 得到图片的高宽
    	int width = target.getWidth();
    	int height = target.getHeight();
    	Matrix matrix = new Matrix();
    	// 算出图片的高宽缩放比例
    	float scaleWidth = ((float)300)/ width;
    	float scaleHeight = ((float)300)/ height;
    	matrix.postScale(scaleWidth, scaleHeight);
//    	Bitmap result = Bitmap.createBitmap(target,0,0,width,height, matrix,true);
    	return Bitmap.createBitmap(target,0,0,width,height, matrix,true);
    }
    
}

 // main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
 <Button android:id="@+id/but" android:text="button" android:layout_width="fill_parent" android:layout_height="wrap_content" />
 <ImageButton android:id="@+id/img" android:layout_width="300dip" android:layout_height="300dip"/>
</LinearLayout>

猜你喜欢

转载自ychengit.iteye.com/blog/1627277
今日推荐