ImageView显示为从解析中获取文件的圆圈

时间:2016-05-10 19:50:53

标签: android parsing bitmap imageview

我已经四处搜索但无法使其正常工作。 我需要找到一种方法,将图像显示为圆形,同时从Parse中获取图像。

我有麻烦,因为我有一些代码在MainActivity,doInBackground(),以获取我的解析数据,左图像(奥尔巴尼)和ListViewAdapter,在getView()我设置位图将图像转为圆形,右一个(德国)取自当地人。

My achieves so far(左图来自Parse,右图来自本地(可画))。

希望你能帮助我一点,提前谢谢!
这是我的活动/布局:

MainActivity.java

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

public static final String YOUR_APPLICATION_ID = "XXXXXXXXX";
public static final String YOUR_CLIENT_KEY = "XXXXXXXX";

// Declare Variables
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
ListViewAdapter adapter;
private List<WorldPopulation> worldpopulationlist = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Get the view from listview_main.xml
    //setContentView(R.layout.activity_main);
    // Execute RemoteDataTask AsyncTask
    new RemoteDataTask().execute();

    //Parse.initialize(this, YOUR_APPLICATION_ID, YOUR_CLIENT_KEY);

    ParseObject testObject = new ParseObject("TestObject");
    testObject.put("foo", "bar");
    testObject.saveInBackground();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

}

// RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Parse.com Custom ListView Tutorial");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        **SETS LEFT IMAGE TAKING DATA FROM PARSE**
        worldpopulationlist = new ArrayList<WorldPopulation>();
        try {
            // Locate the class table named "Country" in Parse.com
            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                    "Country");
            // Locate the column named "ranknum" in Parse.com and order list
            // by ascending
            query.orderByAscending("ranknum");
            ob = query.find();
            for (ParseObject country : ob) {
                // Locate images in flag column
                ParseFile image = (ParseFile) country.get("flag");

                WorldPopulation map = new WorldPopulation();
                map.setRank((String) country.get("rank"));
                map.setCountry((String) country.get("country"));
                map.setPopulation((String) country.get("population"));
                map.setFlag(image.getUrl());
                worldpopulationlist.add(map);
            }
        } catch (ParseException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listView);
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(MainActivity.this,
                worldpopulationlist);
        // Binds the Adapter to the ListView
        listview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }
}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
  }
}

ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter {

// Declare Variables
Context context;
LayoutInflater inflater;
ImageLoader imageLoader;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;

ImageView mImage;
Bitmap bm;

public ListViewAdapter(Context context,
                       List<WorldPopulation> worldpopulationlist) {
    this.context = context;
    this.worldpopulationlist = worldpopulationlist;
    inflater = LayoutInflater.from(context);
    this.arraylist = new ArrayList<WorldPopulation>();
    this.arraylist.addAll(worldpopulationlist);
    imageLoader = new ImageLoader(context);
}

public class ViewHolder {
    TextView rank;
    TextView country;
    TextView population;
    ImageView flag;
}

@Override
public int getCount() {
    return worldpopulationlist.size();
}

@Override
public Object getItem(int position) {
    return worldpopulationlist.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public View getView(final int position, View view, ViewGroup parent) {
    final ViewHolder holder;
    if (view == null) {
        holder = new ViewHolder();
        view = inflater.inflate(R.layout.listview_item, null);
        // Locate the TextViews in listview_item.xml
        holder.rank = (TextView) view.findViewById(R.id.local);
        //holder.country = (TextView) view.findViewById(R.id.country);
        holder.population = (TextView) view.findViewById(R.id.visitor);
        // Locate the ImageView in listview_item.xml
        holder.flag = (ImageView) view.findViewById(R.id.flagLocalTeam);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }
    // Set the results into TextViews
    holder.rank.setText(worldpopulationlist.get(position).getRank());
   // holder.country.setText(worldpopulationlist.get(position).getCountry());
    holder.population.setText(worldpopulationlist.get(position)
            .getPopulation());
    // Set the results into ImageView
     **SETS RIGHT IMAGE TAKING DATA FROM LOCAL(drawable)**
    imageLoader.DisplayImage(worldpopulationlist.get(position).getFlag(),
            holder.flag);

    bm = BitmapFactory.decodeResource(context.getResources(),
            R.drawable.ger);

    // set circle bitmap
    mImage = (ImageView) view.findViewById(R.id.flagVisitorTeam);
    mImage.setImageBitmap(getCircleBitmap(bm));
    // Listen for ListView Item Click
    view.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Send single item click data to SingleItemView Class
            Intent intent = new Intent(context, SingleItemView.class);
            // Pass all data rank
            intent.putExtra("rank",
                    (worldpopulationlist.get(position).getRank()));
            // Pass all data country
            intent.putExtra("country",
                    (worldpopulationlist.get(position).getCountry()));
            // Pass all data population
            intent.putExtra("population",
                    (worldpopulationlist.get(position).getPopulation()));
            // Pass all data flag
            intent.putExtra("flag",
                    (worldpopulationlist.get(position).getFlag()));
            // Start SingleItemView Class
            context.startActivity(intent);
        }
    });
    return view;
}


private Bitmap getCircleBitmap(Bitmap bitmap) {
    final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(output);

    final int color = Color.RED;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawOval(rectF, paint);

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

    bitmap.recycle();

    return output;
   }

}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

listview_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<ImageView
    android:id="@+id/flagLocalTeam"
    android:layout_width="100dp"
    android:layout_height="100dp" />

<TextView
    android:id="@+id/local"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Local"
    android:layout_toRightOf="@+id/flagLocalTeam" />

<TextView
    android:id="@+id/vs"
    android:text="VS"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="10dp"
    android:layout_marginLeft="10dp"
    android:layout_toRightOf="@+id/local" />

<TextView
    android:id="@+id/visitor"
    android:text="Visitante"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/vs" />

<ImageView
    android:id="@+id/flagVisitorTeam"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true"
    android:scaleType="fitXY"/>

</RelativeLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.corsica.proyectox.MainActivity"
tools:showIn="@layout/app_bar_main">


<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">


    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView" />
</LinearLayout>
</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

替换此getCircleBitmap

public Bitmap getCircleBitmap(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

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

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
}

我有类似的情况,但我从Bitmap转换Base64并且工作正常。

final byte[] decodedString = Base64.decode(mProfile.getPhotoBase64(), Base64.DEFAULT);
final Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
final Bitmap newBitmap = getCircleBitmap(bitmap);
mImage.setImageBitmap(newBitmap);

也许这可以帮助您找到解决方案。

答案 1 :(得分:0)

刚刚找到了一个允许我按照自己的意愿去做的图书馆。 试过毕加索,但没有得到上下文,所以我使用: https://github.com/hdodenhof/CircleImageView

现在我改变了一些我的代码,所以,首先我从Parse带来我的图像,然后使用我能够改变的库。

是的,我找到这个解决方案后觉得有点愚蠢