Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> UI控件之顯示圖像控件ImageView(下)

UI控件之顯示圖像控件ImageView(下)

編輯:關於Android編程

(一)繪制最簡單的圓形ImageView
這裡寫圖片描述
RoundedImageView

CircleImageView

運行效果:
這裡寫圖片描述

實現代碼:

自定義ImageView代碼:

package com.example.android_drawable_xml;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundImageView extends ImageView {

    private Bitmap mBitmap;
    private Rect mRect = new Rect();
    private PaintFlagsDrawFilter pdf=new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG);
    private Paint mPaint = new Paint();
    private Path mPath =  new Path();


    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    //傳入一個Bitmap對象
    public void setmBitmap(Bitmap bitmap) {
        this.mBitmap = bitmap;
    }

    private void init(){
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);//抗鋸齒
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mBitmap == null) {
            return;

        }
        mRect.set(0,0,getWidth(),getHeight());
        canvas.save();
        canvas.setDrawFilter(pdf);
        mPath.addCircle(getWidth() / 2 , getWidth() / 2 , getHeight() / 2 , Path.Direction.CCW);
        canvas.clipPath(mPath,Region.Op.REPLACE);
        canvas.drawBitmap(mBitmap, null, mRect, mPaint);
        canvas.restore();
    }
}

MainActivity.java

package com.example.android_drawable_xml;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;



public class MainActivity extends Activity {

    private RoundImageView img_roundImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        RoundImageView img_roundImageView = (RoundImageView) findViewById(R.id.img_round);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bulunou);

        img_roundImageView.setmBitmap(bitmap);
    }

}

activity_main.xml文件



   

(二)ImageView實現圖片裁剪和顯示的功能
網上一張圖:
這裡寫圖片描述
這個是QQ的剪切圖來設置頭像的,其實就是一個ImageView的剪切與顯示;
運行結果:
這裡寫圖片描述
做的比較粗糙~~~你可以在此基礎上精雕細琢下~
實現代碼:<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;"> package com.example.android_imageview; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class CutImageView extends Activity implements OnClickListener{ private Button selectImageBtn; private Button cutImageBtn; private ImageView imageView; // 聲明兩個靜態的整型變量,主要是用於意圖的返回的標志 private static final int IMAGE_SELECT = 1;// 選擇圖片 private static final int IMAGE_CUT = 2;// 裁剪圖片 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cut_imageview); selectImageBtn = (Button) this.findViewById(R.id.selectImgBtn); cutImageBtn = (Button) this.findViewById(R.id.cutImageBtn); imageView = (ImageView) this.findViewById(R.id.imageview3); selectImageBtn.setOnClickListener(this); cutImageBtn.setOnClickListener(this); // imageView.setImageBitmap(bm); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { // 處理圖片按照手機的屏幕大小顯示 if (requestCode == IMAGE_SELECT) { Uri uri = data.getData();// 獲得圖片的路徑 int dw = getWindowManager().getDefaultDisplay().getWidth();// 獲得屏幕的寬度 int dh = getWindowManager().getDefaultDisplay().getHeight() / 2; try { // 實現對圖片的裁剪的類,是一個匿名內部類 BitmapFactory.Options factory = new BitmapFactory.Options(); factory.inJustDecodeBounds = true;// 如果設置為true,允許查詢圖片不是按照像素分配給內存 Bitmap bmp = BitmapFactory.decodeStream( getContentResolver().openInputStream(uri), null, factory); // 對圖片的寬度和高度對應手機的屏幕進行匹配 int hRatio = (int) Math .ceil(factory.outHeight / (float) dh); // 如果大於1 表示圖片的高度大於手機屏幕的高度 int wRatio = (int) Math.ceil(factory.outWidth / (float) dw); // 如果大於1 表示圖片的寬度大於手機屏幕的寬度 // 縮放到1/radio的尺寸和1/radio^2像素 if (hRatio > 1 || wRatio > 1) { if (hRatio > wRatio) { factory.inSampleSize = hRatio; } else { factory.inSampleSize = wRatio; } } // 對 factory.inJustDecodeBounds = false; // 使用BitmapFactory對圖片進行適屏的操作, bmp = BitmapFactory.decodeStream(getContentResolver() .openInputStream(uri), null, factory); imageView.setImageBitmap(bmp); } catch (Exception e) { // TODO: handle exception } // 表示裁剪圖片 } else if (requestCode == IMAGE_CUT) { Bitmap bitmap = data.getParcelableExtra("data"); imageView.setImageBitmap(bitmap); } } } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.selectImgBtn: // 如何提取手機的圖片的,並且進行選擇圖片的功能 Intent intent = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 打開手機的圖片庫 startActivityForResult(intent, IMAGE_SELECT); break; case R.id.cutImageBtn: Intent intent2 = getImageClipIntent(); startActivityForResult(intent2, IMAGE_CUT); break; } } private Intent getImageClipIntent() { // TODO Auto-generated method stub Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); // 實現對圖片的裁剪,必須要設置圖片的屬性和大小 intent.setType("image/*");// 獲取任意的圖片類型 intent.putExtra("crop", "true");// 滑動選中圖片區域 intent.putExtra("aspectX", 1);// 表示剪切框的比例1:1的效果 intent.putExtra("aspectY", 1); intent.putExtra("outputX", 80);// 指定輸出圖片的大小 intent.putExtra("outputY", 80); intent.putExtra("return-data", true); return intent; } }

cut_imageview.xml


(三)ImageView實現圖片圖片旋轉
在開發中實現對圖像的縮放有很多方法,最簡單的方法是改變ImageView控件的大小,我們只要將標簽的android:scaleType的屬性值設置為fitCenter,
要是想實現圖像的旋轉可以使用android.graphics.Matirx類的setRotate來實現.

運行效果如下:
這裡寫圖片描述

實現代碼:

public class ImageViewRotateText extends Activity  implements OnSeekBarChangeListener{

    private int minWidth=80;
    private ImageView imageView;
    private TextView textView1 ,textView2;
    private Matrix matrix = new Matrix();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rotate_imageview);
        imageView = (ImageView) this.findViewById(R.id.imageview5);
        SeekBar seekBar1 = (SeekBar) this.findViewById(R.id.seekbar1);
        SeekBar seekBar2 = (SeekBar) this.findViewById(R.id.seekbar2);
        textView1 = (TextView) this.findViewById(R.id.textview1);
        textView2 = (TextView) this.findViewById(R.id.textview2);
        seekBar1.setOnSeekBarChangeListener(this);
        seekBar2.setOnSeekBarChangeListener(this);

        //
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        seekBar1.setMax(dm.widthPixels - minWidth);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromUser) {
        // TODO Auto-generated method stub
        if (seekBar.getId() == R.id.seekbar1) {
            int newWidth = progress + minWidth;
            int newHeight = (int)(newWidth * 3 / 4);//按照原圖進行縮放的功能
            imageView.setLayoutParams( new LinearLayout.LayoutParams(newWidth , newHeight));
            textView1.setText("圖像寬度:  "+newWidth+"圖像高度:   "+newHeight);

        }else if (seekBar.getId() == R.id.seekbar2) {
            Bitmap bitmap = ((BitmapDrawable)(getResources()
                    .getDrawable(R.drawable.xingkong))).getBitmap();
            matrix.setRotate(progress);//設置翻轉的角度
            bitmap = Bitmap.createBitmap(bitmap ,0,0,bitmap.getWidth(),
                    bitmap.getHeight() , matrix, true);
            imageView.setImageBitmap(bitmap);
            textView2.setText(progress+"度");


        }

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

    }




}

xml文件


(四)使用ImageView獲取網絡圖片
運行效果:
這裡寫圖片描述

實現代碼:
xml文件



    

    

main.java

public class Main extends Activity {

    private Button button;
    private ImageView imageView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button) this.findViewById(R.id.button);
        imageView = (ImageView) this.findViewById(R.id.imageview);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // try {
                // InputStream inputStream = HttpUtils
                // .getImageViewInputStream();
                // Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                // imageView.setImageBitmap(bitmap);
                // } catch (IOException e) {
                // // TODO: handle exception
                // }
                byte[] data = HttpUtils.getImageViewArray();
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
                        data.length);
                imageView.setImageBitmap(bitmap);

            }
        });
    }
}

使用Http協議獲取網絡圖片
HttpUtils.java

public class HttpUtils {

    private final static String URL_PATH = "http://img.my.csdn.net/uploads/201202/8/0_13287131646nNZ.gif";// 訪問網路圖片的路徑

    public HttpUtils() {
        // TODO Auto-generated constructor stub
    }

    /**
     * 從網絡中獲取圖片信息,以流的形式返回
     * 
     * @return
     */
    public static InputStream getImageViewInputStream() throws IOException {
        InputStream inputStream = null;

        URL url = new URL(URL_PATH);
        if (url != null) {
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            httpURLConnection.setConnectTimeout(3000);// 設置連接超時的時間
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);
            int response_code = httpURLConnection.getResponseCode();
            if (response_code == 200) {
                inputStream = httpURLConnection.getInputStream();
            }
        }
        return inputStream;
    }

    /**
     * 從網絡中獲取圖片信息,以字節數組的形式返回
     * 
     * @return
     */
    public static byte[] getImageViewArray() {
        byte[] data = null;
        InputStream inputStream = null;
        // 不需要關閉的輸出流,直接寫入到內存中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            URL url = new URL(URL_PATH);
            if (url != null) {
                HttpURLConnection httpURLConnection = (HttpURLConnection) url
                        .openConnection();
                httpURLConnection.setConnectTimeout(3000);// 設置連接超時的時間
                httpURLConnection.setRequestMethod("GET");// 請求方法
                httpURLConnection.setDoInput(true);// 打開輸入流
                int response_code = httpURLConnection.getResponseCode();
                int len = 0;
                byte[] b_data = new byte[1024];

                if (response_code == 200) {
                    inputStream = httpURLConnection.getInputStream();
                    while ((len = inputStream.read(b_data)) != -1) {
                        outputStream.write(b_data, 0, len);
                    }
                    data = outputStream.toByteArray();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return data;
    }
}

不懂地方記得問搜索額,(~﹃~)~zZ <完>

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved