如何以圆形格式转换ImageView的图像

时间:2014-04-03 11:27:56

标签: android bitmap android-imageview

目前我正在处理应用程序,其中我在按钮点击时翻转图像。但问题在于我正在使用来自xml的ImageView图像,这些图像是矩形格式。我想以圆形格式使用这些图像。

我在互联网上搜索这个问题,我发现大多数解决方案都使用Bitmap图像。 这意味着我需要以位图格式转换图像。我怎样才能转换这些。
注意: - 我正在使用Drawable文件夹中的图像。

我找到了这些解决方案,但不知道如何使用它们:
How to make an ImageView with rounded corners?

第二个:
How to create a circular ImageView in Android?



如何在我的应用中使用这些解决方案?
那么如何转换圆形图像?

这是我的MainActivity.java课程,我用它在按钮点击时翻转图像。


package com.example.image_changer;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends Activity {
TextView textView;
ImageView imageView;
ImageView imageView1;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMillisecond = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
Button button;
Button button2;
Button button3;
Button music;
boolean pause;
int flag=0;;
VideoView videoView;

MediaController mediaController;






MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // MainActivity.this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    // MainActivity.this.getWindow().setFlags(
    // WindowManager.LayoutParams.FLAG_FULLSCREEN,
    // WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_main);

    mp = new MediaPlayer();
    mp= MediaPlayer.create(this, R.raw.instrumental);


    textView = (TextView) findViewById(R.id.timerValue);
    button = (Button) findViewById(R.id.button1);
    button3 = (Button)findViewById(R.id.button2);
    button2 = (Button) findViewById(R.id.pause);
    music = (Button)findViewById(R.id.button3);
    imageView1 = (ImageView) findViewById(R.id.imageView4);
    videoView = (VideoView) findViewById(R.id.videoView1);  


    imageView1.buildDrawingCache();
    Bitmap bmap = imageView1.getDrawingCache();


    videoView.setVisibility(1);
    imageView1.setVisibility(1);


    mediaController = new MediaController(MainActivity.this);
    // RelativeLayout relativeLayout = (RelativeLayout)
    // findViewById(R.id.relativelayout);
    // relativeLayout.setBackgroundResource(R.drawable.img);

    Typeface typeface = Typeface.createFromAsset(getAssets(),
            "font/gothic_0.TTF");
    button.setTypeface(typeface);
    button2.setTypeface(typeface);
    button3.setTypeface(typeface);
    music.setTypeface(typeface);
    button.setVisibility(1);
    button2.setVisibility(1);
    button2.setVisibility(View.INVISIBLE);
    textView.setVisibility(View.INVISIBLE);
    videoView.setVisibility(View.INVISIBLE);
    imageView1.setVisibility(View.INVISIBLE);

    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#ee7b35")));

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            textView.setVisibility(View.VISIBLE);
            button.setVisibility(View.INVISIBLE);
            button2.setVisibility(View.VISIBLE);
            videoView.setVisibility(View.GONE);
            imageView1.setVisibility(View.VISIBLE);

            new CountDownTimer(11000, 7000) {

                @Override
                public void onTick(long millisUntilFinished) {

                    customHandler.postDelayed(updateTimerThread, 1);
                    startTime = SystemClock.uptimeMillis();
                }

                @Override
                public void onFinish() {
                    customHandler.removeCallbacks(updateTimerThread);
                }
            }.start();

            // TODO Auto-generated method stub
        }
    });



    button2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            customHandler.removeCallbacks(updateTimerThread);
            button.setVisibility(View.VISIBLE);
            button2.setVisibility(View.INVISIBLE);
            imageView1.setVisibility(View.GONE);
            videoView.setVisibility(View.GONE);

        }
    });


    button3.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            textView.setVisibility(View.INVISIBLE);
            videoView.setVisibility(View.VISIBLE);
            imageView1.setVisibility(View.GONE);
            button.setVisibility(View.VISIBLE);
            button2.setVisibility(View.INVISIBLE);

                ArrayList<Integer> songarr= new ArrayList<Integer>();
                songarr.add(R.raw.funny);
                Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.funny);
               mediaController.setAnchorView(videoView);
               videoView.setMediaController(mediaController);
               videoView.setVideoURI(uri);
               videoView.start(); 
               }
                });


     videoView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            // TODO Auto-generated method stub
            if (flag == 0){

                button.setVisibility(View.INVISIBLE);
                button2.setVisibility(View.INVISIBLE);
                music.setVisibility(View.INVISIBLE);
                button3.setVisibility(View.INVISIBLE);
             DisplayMetrics metrics = new DisplayMetrics();
             getWindowManager().getDefaultDisplay().getMetrics(metrics);
             android.widget.RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) videoView.getLayoutParams();
             params.width =  metrics.widthPixels;
             params.height = metrics.heightPixels;

             //params.leftMargin = 0;
             videoView.setLayoutParams(params);
             flag = 1;
            }else{

                button.setVisibility(View.VISIBLE);
                button2.setVisibility(View.VISIBLE);
                music.setVisibility(View.VISIBLE);
                button3.setVisibility(View.VISIBLE);
             DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics);
             android.widget.RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) videoView.getLayoutParams();
             params.width =  (int) (200*metrics.density);
             params.height = (int) (200*metrics.density);
             params.leftMargin = 30;
             videoView.setLayoutParams(params);
            flag = 0;
            }

            return false;
        }
    });











    music.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(flag == 0){

            Toast.makeText(getApplicationContext(), "Playing Music", Toast.LENGTH_LONG).show();
            mp.start();

            flag = 1;
            }
            else{
                Toast.makeText(getApplicationContext(), "Stop", Toast.LENGTH_LONG).show();
                mp.stop();
                mp.release();
                flag = 0;
            }



        }
    });











            }




private Runnable updateTimerThread = new Runnable() {

    int secs;

    @Override
    public void run() {
        // TODO Auto-generated method stub
        timeInMillisecond = SystemClock.uptimeMillis() - startTime;
        updatedTime = timeSwapBuff + timeInMillisecond;
        secs = (int) (updatedTime / 1000);
        int mins = secs / 60;
        secs = secs % 60;
        int milliseconds = (int) (updatedTime % 10000);
        textView.setText(String.format("%02d", secs));

        customHandler.postDelayed(this, 1000);


        switch (secs) {
        case 1:
            imageView1.setBackgroundResource(R.drawable.img1);
            break;
        case 2:
            imageView1.setBackgroundResource(R.drawable.img2);
            break;
        case 3:
            imageView1.setBackgroundResource(R.drawable.img3);
            break;
        case 4:
            imageView1.setBackgroundResource(R.drawable.img4);
            break;
        case 5:
            imageView1.setBackgroundResource(R.drawable.img5);
            break;
        case 6:
            imageView1.setBackgroundResource(R.drawable.img6);
            break;
        case 7:
            imageView1.setBackgroundResource(R.drawable.img7);
            break;
        case 8:
            imageView1.setBackgroundResource(R.drawable.img8);
            break;
        case 9:
            imageView1.setBackgroundResource(R.drawable.img9);
            break;
        case 10:
            imageView1.setBackgroundResource(R.drawable.img66);
            button.setVisibility(View.VISIBLE);
            button2.setVisibility(View.INVISIBLE);
            break;
        }
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    // return super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    // return super.onOptionsItemSelected(item);
    if (item.getItemId() == R.id.menulist)
        finish();

    // return true;
    if (item.getItemId() == R.id.pager1) {
        Intent in = new Intent(getApplicationContext(), MainActivity1.class);
        startActivity(in);

    }

    if (item.getItemId() == R.id.image1) {
        Intent in = new Intent(getApplicationContext(), Imageswipe.class);
        startActivity(in);

    }
    return true;
}

}

这是我的xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativelayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF944D"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/timerValue"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="14dp"
    android:textColor="#ffffff"
    android:text="00"
    android:textSize="40sp" />

<Button
    android:id="@+id/pause"
    android:layout_width="50dp"
    android:layout_height="200dp"
    android:layout_alignParentRight="true"
    android:layout_alignRight="@+id/button1"
    android:layout_centerVertical="true"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="6dp"
    android:background="#ee7b35"
    android:padding="20dp"
    android:text="Pause"
    android:textColor="#ffffff"
    />

<Button
    android:id="@+id/button1"
    android:layout_width="200dp"
    android:layout_height="50dp"
    android:layout_below="@+id/pause"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="5dp"
    android:layout_marginTop="4dp"
    android:background="#ee7b35"
    android:text="Start slide show"
    android:textColor="#ffffff" />

<Button
    android:id="@+id/button2"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1"
    android:layout_toLeftOf="@+id/timerValue"
    android:background="#2B9B2B"
    android:textColor="#ffffff"
    android:text="Play Video" />

<Button
    android:id="@+id/button3"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignRight="@+id/button1"
    android:layout_below="@+id/button1"
    android:layout_toRightOf="@+id/timerValue"
    android:background="#3B38FD"
    android:textColor="#ffffff"
    android:text="Play Audio" />

<VideoView
    android:id="@+id/videoView1"
    android:layout_width="200dp"
    android:layout_height="200dp"

    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

<ImageView
    android:id="@+id/imageView4"
    android:layout_width="200dp"
    android:layout_height="200dp"

    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"

     />

</RelativeLayout>

2 个答案:

答案 0 :(得分:1)

尝试使用github上的CircularImageView库。

<强> XML:

<com.mikhaellopez.circularimageview.CircularImageView
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:src="@drawable/image"
        app:border_color="#EEEEEE"
        app:border_width="10"
        app:shadow="true" />

<强>爪哇:

CircularImageView circularImageView = (CircularImageView)findViewById(R.id.yourCircularImageView);
circularImageView.setBorderColor(getResources().getColor(R.color.GrayLight));
circularImageView.setBorderWidth(10);
circularImageView.addShadow();

答案 1 :(得分:1)

简单

xml文件中的

只需拖动imageview并从可绘制文件夹中放入任何图像

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"       
    android:layout_centerHorizontal="true"       
    android:src="@drawable/image" />
主要活动中

获取图像视图的所有控件。通过使用位图,我们可以将图像裁剪成圆形,并在同一图像视图中显示。不仅是圆形,我们可以使用它将它转换成任何形状,如方形或左右。

public class MainActivity extends Activity {

static ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imageView=(ImageView)findViewById(R.id.imageView1);

    Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.image);

    imageView.setImageBitmap(getCircleBitmap(bitmap));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


public static Bitmap getCircleBitmap(Bitmap bitmap) {


    //crop to circle 
    Bitmap output;
    //check if its a rectangular image
    if (bitmap.getWidth() > bitmap.getHeight()) {
        output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Config.ARGB_8888);
    } else {
        output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Config.ARGB_8888);
    }
    Canvas canvas = new Canvas(output);

    float r = 0;

    if (bitmap.getWidth() > bitmap.getHeight()) {
        r = bitmap.getHeight() / 2;
    } else {
        r = bitmap.getWidth() / 2;
    }

    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());


    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);

    canvas.drawCircle(r, r, r, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
   }

}