Sunday, December 29, 2013

CircularImageView Using Custom View

20 comments :
Hi,

This is an Example for CustomView extends View Class.

Introduction:

     Own view typically classified as custom views and compound views.

     compound views are constructor based on existing views with some predefined layout and logic
and it extends on View group class.

     custom view extends view class and draw on themselves

Creating custom view:

    By extending viewclass or one of its subclass you can create your own view.It is responsible for measuring,layouting,drawing themselves and their child elements and also saving UI state  and handling touch events.

Reason for creating view:

   View are typically created to avoid repetition code

CutomView.class:


package com.example.circularImageview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CustomView extends ImageView
{

private  int color;
    private  Paint paint;
    private  Rect rect;
    private  RectF rectF;
    private  Bitmap output;
    private  Canvas canvas;
    private  float roundPx;

public CustomView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}


public CustomView(Context context, AttributeSet attrs, int defStyle) 
{
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(),getMeasuredWidth());
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
 // TODO Auto-generated method stub
 int targetWidth = 1000;
 int targetHeight =630;
 Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
                           targetHeight,Bitmap.Config.ARGB_8888);
 Canvas canvas = new Canvas(targetBitmap);
 Path path = new Path();
 path.addCircle(((float) targetWidth - 1) / 2,
 ((float) targetHeight) / 2,(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
         Path.Direction.CCW);
 //path.addCircle(50,50,50,Path.Direction.CCW);
 
               canvas.clipPath(path);
 Bitmap sourceBitmap = scaleBitmapImage;
 canvas.drawBitmap(sourceBitmap, 
                               new Rect(0, 0, sourceBitmap.getWidth(),
   sourceBitmap.getHeight()), 
                               new Rect(0, 0, targetWidth,
   targetHeight), null);
 return targetBitmap;
}
}

MainActivity.java:


package com.example.circularImageview;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private LruCache<String, Bitmap> mMemoryCache;
GridView gd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gd=(GridView)findViewById(R.id.gridView1);
gd.setAdapter(new MyAdapter(this));
gd.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
 
  Toast.makeText(getApplicationContext(),"your position is  "+arg2, 4).show();   
                   
}

});

}

public class MyAdapter extends BaseAdapter
{
          
private List<Item> items=new ArrayList<Item>();
private LayoutInflater inflator;
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
inflator=LayoutInflater.from(context);
items.add(new Item("nature1",R.drawable.img1));
items.add(new Item("nature2",R.drawable.img2));
items.add(new Item("nature3",R.drawable.img3));
items.add(new Item("nature4",R.drawable.img4));
items.add(new Item("nature5", R.drawable.img5));
items.add(new Item("nature6",R.drawable.img2));
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return items.get(position).drawableId;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) 
{
// TODO Auto-generated method stub
View v=convertView;
ImageView img1;
TextView txt1;
if(v==null)
{
v=inflator.inflate(R.layout.grid_item,parent,false);
v.setTag(R.id.picture,v.findViewById(R.id.picture));
v.setTag(R.id.text,findViewById(R.id.text));
}
   img1=(ImageView)v.findViewById(R.id.picture);
   txt1=(TextView)v.findViewById(R.id.text);
   Item item=(Item)getItem(position);
 //  final String imageKey = String.valueOf(item.drawableId);
   CustomView cv=new CustomView(MainActivity.this);
   //final Bitmap bitmap = mMemoryCache.get(imageKey);
   Bitmap bmp = BitmapFactory.decodeResource(getResources(), item.drawableId);  
   img1.setImageBitmap(cv.getRoundedShape(bmp));
  // img1.setImageResource(item.drawableId);
   txt1.setText(item.name);
return v;
}
}
private class Item
{
final String name;
final int drawableId;
Item(String name,int drawableId)
{
  this.name=name;
  this.drawableId=drawableId;
  
}
}

}


activity_main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/FrameLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
     >

    <GridView
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:gravity="center"
        android:stretchMode="columnWidth"
        android:numColumns="auto_fit"
       >
    </GridView>

</FrameLayout>


list.xml:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" 
        >

    </ListView>

</RelativeLayout>



Here the Output is shown below







20 comments :

  1. This comment has been removed by the author.

    ReplyDelete
  2. can u share a sorce code of this project?

    ReplyDelete
  3. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    java training in marathahalli | java training in btm layout

    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    selenium training in chennai

    ReplyDelete
  4. I simply want to give you a huge thumbs up for the great info you have got here on this post.
    python training in pune
    python online training
    python training in OMR

    ReplyDelete
  5. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs Training in bangalore

    angularjs Training in bangalore

    ReplyDelete
  6. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete
  7. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks; from every one of us.
    iosh course in chennai

    ReplyDelete

  8. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.

    Web Designing Training in Chennai | Best Web Designing Training in Chennai
    RPA Training in Chennai | Best RPA Training in Chennai

    ReplyDelete
  9. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. I need to to thank you for this great read!! Technology I absolutely loved every little bit of it. I've got you book-marked to check out new stuff you post…

    ReplyDelete
  12. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.nic e blog.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  13. Sharing the same interest, Infycle feels so happy to share our detailed information about all these courses with you all! Do check them out
    Big data training in chennai & get to know everything you want to about software trainings

    ReplyDelete
  14. Title:
    Big Data Hadoop Training in Chennai | Infycle Technologies

    Description:
    Learn Hadoop Training in Chennai for making your career towards a sky-high with Infycle Technologies. Infycle Technologies offers the best Big Data Hadoop training in Chennai, providing courses for Big Data in 200% hands-on practical training with professional trainers in the domain. Apart from the coaching, the placement interviews will be arranged for the students, so that they can set their career without any struggle. Of all that, 100% placement assurance will be given here. To have the best career, call 7502633633 to Infycle Technologies and grab a free demo to know more.
    best training institute in chennai

    ReplyDelete