Circular imageview with downloading from url - android

I am downloading image from url with ion library.It is working like this:
holder.imageView=(ImageView)convertView.findViewById(R.id.image);
Ion.with(holder.imageView).load(image_url);
My imageView xml:
<ImageView
android:id="#+id/image"
android:layout_width="64dp"
android:layout_height="64dp"
android:src="#drawable/defaultprofile"/>
I want to use this imageview as circular imageview.
I have found that question:How to Make an ImageView in Circular Shape?
But in that question they are using static image.I mean they don't download from url.How can I use circular image with downloading from url or what is the best library for me ?

Use Picasso. It is the best (for me) image downloading library which also handles caching. https://github.com/square/picasso You can also set a placeholder while the image is loading and you can do so much more than that.
For the circular ImageView you can use this library: https://github.com/hdodenhof/CircleImageView or one of the others Butani Vijay gave, but you can also use transformation specifically for Picasso: https://gist.github.com/julianshen/5829333
I'm using Picasso with this transformation method in my own apps.

You can use any one of below :
https://github.com/hdodenhof/CircleImageView
https://github.com/Pkmmte/CircularImageView
https://github.com/lopspower/CircularImageView
You need to create custome ImageView
Example :
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CircularImageView extends ImageView {
private int borderWidth;
private int canvasSize;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
public CircularImageView(final Context context) {
this(context, null);
}
public CircularImageView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.circularImageViewStyle);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// init paint
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
// load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);
if(attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics().density + 0.5f);
setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
}
if(attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
addShadow();
}
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
this.requestLayout();
this.invalidate();
}
public void setBorderColor(int borderColor) {
if (paintBorder != null)
paintBorder.setColor(borderColor);
this.invalidate();
}
public void addShadow() {
setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
}
#Override
public void onDraw(Canvas canvas) {
// load the bitmap
image = drawableToBitmap(getDrawable());
// init shader
if (image != null) {
canvasSize = canvas.getWidth();
if(canvas.getHeight()<canvasSize)
canvasSize = canvas.getHeight();
BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
// circleCenter is the x or y of the view's center
// radius is the radius in pixels of the cirle to be drawn
// paint contains the shader that will texture the shape
int circleCenter = (canvasSize - (borderWidth * 2)) / 2;
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder);
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// The parent has determined an exact size for the child.
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// The parent has not imposed any constraint on the child.
result = canvasSize;
}
return result;
}
private int measureHeight(int measureSpecHeight) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = canvasSize;
}
return (result + 2);
}
public Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) {
return null;
} else if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
And use as below in your layout :
<com.yourpkg.CircularImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:src="#drawable/image"
app:border="true"
app:border_color="#color/GrayLight"
app:border_width="4dp"
app:shadow="true" />

Related

Round shape image without other library

I need get image from external memory and place that image into round shape
And also save that image into sheredprefernce
I tried may way but I can't make it
I need it to done without any external library
For Rounded imageview without any library you can use the below class.
package com.sample;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Custom Circular Image view.
*/
public class RoundImageview extends ImageView {
private int borderWidth = 0;
private int viewWidth;
private int viewHeight;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
private Paint shaderPaint;
private BitmapShader shader;
private static int mBorderColor = android.R.color.white;
private Context context;
private boolean needToDrawOverlay = true;
private AttributeSet attrs;
public RoundImageview(final Context context) {
super(context);
this.context = context;
}
public RoundImageview(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.attrs = attrs;
init();
}
public RoundImageview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
this.attrs = attrs;
init();
}
/**
* To initialize the paint components.
*/
private void init() {
Resources res = context.getResources();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView, 0, 0);
int backgroundColor = a.getColor(R.styleable.RoundImageView_bg_color,
res.getColor(android.R.color.darker_gray));
a.recycle();
paint = new Paint();
paint.setAntiAlias(true);
shaderPaint = new Paint();
shaderPaint.setAntiAlias(true);
shaderPaint.setColor(backgroundColor);
shaderPaint.setStyle(Paint.Style.FILL);
paintBorder = new Paint();
paintBorder.setColor(mBorderColor);
borderWidth = 2;
paintBorder.setAntiAlias(true);
}
#Override
public void onDraw(Canvas canvas) {
// load the bitmap
BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();
if (bitmapDrawable != null) {
image = bitmapDrawable.getBitmap();
}
if (needToDrawOverlay) {
int circleCenter = viewWidth / 2;
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter
+ borderWidth - 4.0f, shaderPaint);
}
// init shader
if (image != null) {
shader = createBitmapShader(image, canvas);
paint.setShader(shader);
// calculate the center point.
int circleCenter = viewWidth / 2;
// circleCenter is the x or y of the view's center
// radius is the radius in pixels of the cirle to be drawn
// paint contains the shader that will texture the shape
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, circleCenter
+ borderWidth - 4.0f, paintBorder);
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth,
circleCenter - 4.0f, paint);
}
}
/**
* To create bitmap shader.
*
* #param image
* #param canvas
* #return BitmapShader object
*/
private BitmapShader createBitmapShader(Bitmap image, Canvas canvas) {
return new BitmapShader(Bitmap.createScaledBitmap(image, this.getWidth(), this.getHeight(),
false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec, widthMeasureSpec);
viewWidth = width;
viewHeight = height;
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = viewWidth;
}
return result;
}
private int measureHeight(int measureSpecHeight, int measureSpecWidth) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = viewHeight;
}
return (result);
}
}
Create a attrs.xml in the values module of the res module
<!-- Round Image view -->
<declare-styleable name="RoundImageView">
<attr name="bg_color" format="color" />
<attr name="border_color" format="color" />
</declare-styleable>
Use it in your layout this way
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:roundImageview="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.sample.RoundImageview
android:id="#+id/imageButton"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:src="#drawable/image"
roundImageview:bg_color="#000000" />
</RelativeLayout>

make an ImageView with rounded corners?

rounded corners of cardview
I want to make the interface as shown above. The images are not fixed, which means I can transfer images to other. I want to use pakage in xml file. Something like,
<com.example.widgets.RoundedImageView
    android: layout_width = "39dp"
    android: layout_height = "39dp"
    android: src = "# drawable / your_drawable" />
you can use this component .
https://github.com/pungrue26/SelectableRoundedImageView
<com.utility.SelectableRoundedImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:sriv_left_top_corner_radius="55dp"
app:sriv_right_top_corner_radius="0dp"
android:scaleType="fitXY"
/>
If you do not want to use any third party libraries then you can Customize Your ImageView.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
public class RoundedImageView extends android.support.v7.widget.AppCompatImageView {
private Paint mPaint;
private Path mPath;
private Bitmap mBitmap;
private Matrix mMatrix;
private int mRadius = convertDpToPixel(10);
private int mWidth;
private int mHeight;
private Drawable mDrawable;
public RoundedImageView(Context context) {
super(context);
init();
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.WHITE);
mPath = new Path();
}
public int convertDpToPixel(int dp) {
DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics);
}
#Override
public void setImageDrawable(Drawable drawable) {
mDrawable = drawable;
if (drawable == null) {
return;
}
mBitmap = drawableToBitmap(drawable);
int bDIWidth = mBitmap.getWidth();
int bDIHeight = mBitmap.getHeight();
//Fit to screen.
float scale;
if ((mHeight / (float) bDIHeight) >= (mWidth / (float) bDIWidth)) {
scale = mHeight / (float) bDIHeight;
} else {
scale = mWidth / (float) bDIWidth;
}
float borderLeft = (mWidth - (bDIWidth * scale)) / 2;
float borderTop = (mHeight - (bDIHeight * scale)) / 2;
mMatrix = getImageMatrix();
RectF drawableRect = new RectF(0, 0, bDIWidth, bDIHeight);
RectF viewRect = new RectF(borderLeft, borderTop, (bDIWidth * scale) + borderLeft, (bDIHeight * scale) + borderTop);
mMatrix.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
invalidate();
}
private Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if (bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = MeasureSpec.getSize(widthMeasureSpec);
mHeight = MeasureSpec.getSize(heightMeasureSpec);
if ((mDrawable != null) && (mHeight > 0) && (mWidth > 0)) {
setImageDrawable(mDrawable);
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBitmap == null) {
return;
}
canvas.drawColor(Color.TRANSPARENT);
mPath.reset();
mPath.moveTo(0, mRadius);
mPath.lineTo(0, canvas.getHeight());
mPath.lineTo(canvas.getWidth(), canvas.getHeight());
mPath.lineTo(canvas.getWidth(), mRadius);
mPath.quadTo(canvas.getWidth(), 0, canvas.getWidth() - mRadius, 0);
mPath.lineTo(mRadius, 0);
mPath.quadTo(0, 0, 0, mRadius);
canvas.drawPath(mPath, mPaint);
canvas.clipPath(mPath);
canvas.drawBitmap(mBitmap, mMatrix, mPaint);
}
}
And in layout.xml
<com.example.widget.RoundedImageViewmageView
android:id="#+id/ivProductImg"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="fitXY"
/>
Put imageView in CardView and set CornerRadius for CardView
I already answered in the link below :
Set Round Corner image in ImageView
your drawable code should like this..
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- <solid android:color="add your color here"/>-->
<solid android:color="#00000"/>
<stroke
android:color="add your color here"
android:width="1dp"/>
<corners
android:radius="5dp"/>
</shape>
in XML
<com.example.widgets.RoundedImageView
android: layout_width = "39dp"
android: layout_height = "39dp"
android:background="here is your background source"
android: src = "# drawable / your_drawable"
/>

Creating RoundImageView causes NullPointerException

I want to create RoundedImageView for some ImageView used in my app. I am creating custom view for that.
Below is the Xml file and source code for custom ImageView.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/deleteCallLog"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_margin="4dip" >
<com.nimbuzz.ui.RoundedImageView
android:id="#+id/avatarImage"
android:layout_width="48dip"
android:layout_height="48dip"
android:layout_centerHorizontal="true"
android:src="#drawable/default_avatar" />
<ImageView
android:id="#+id/subCallTypeIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/avatarImage"
android:layout_alignRight="#id/avatarImage"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>
Line: Bitmap bitmap = b.copy(Config.ARGB_8888, true); causing NullPointerException.
It does'nt always happens . On some screens this code works.
RoundedImageView.java:
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onDraw(Canvas canvas)
{
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable)drawable).getBitmap();
Bitmap bitmap = b.copy(Config.ARGB_8888, true);
int w = getWidth(), h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(b, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / factor), (int)(bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius,
Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xffa19774;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(radius / 2 + 0.7f,
radius / 2 + 0.7f, radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
Try this o create own Imageview and directly set the bitmap or resource in imageview..
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;
#SuppressLint("DrawAllocation")
public class RoundedCornerImageView extends ImageView {
public RoundedCornerImageView(Context context) {
super(context);
}
public RoundedCornerImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedCornerImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onDraw(Canvas canvas) {
float radius = 90.0f; // angle of round corners
Path clipPath = new Path();
RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);
super.onDraw(canvas);
}
}
Custom CirularImageView
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
* Custom ImageView for circular images in Android while maintaining the
* best draw performance and supporting custom borders & selectors.
*/
public class CircularImageView extends ImageView {
// For logging purposes
private static final String TAG = CircularImageView.class.getSimpleName();
// Default property values
private static final boolean SHADOW_ENABLED = false;
private static final float SHADOW_RADIUS = 4f;
private static final float SHADOW_DX = 0f;
private static final float SHADOW_DY = 2f;
private static final int SHADOW_COLOR = Color.BLACK;
// Border & Selector configuration variables
private boolean hasBorder;
private boolean hasSelector;
private boolean isSelected;
private int borderWidth;
private int canvasSize;
private int selectorStrokeWidth;
// Shadow properties
private boolean shadowEnabled;
private float shadowRadius;
private float shadowDx;
private float shadowDy;
private int shadowColor;
// Objects used for the actual drawing
private BitmapShader shader;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
private Paint paintSelectorBorder;
private ColorFilter selectorFilter;
public CircularImageView(Context context) {
this(context, null, R.styleable.CircularImageViewStyle_circularImageViewDefault);
}
public CircularImageView(Context context, AttributeSet attrs) {
this(context, attrs, R.styleable.CircularImageViewStyle_circularImageViewDefault);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CircularImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr);
}
/**
* Initializes paint objects and sets desired attributes.
* #param context Context
* #param attrs Attributes
* #param defStyle Default Style
*/
private void init(Context context, AttributeSet attrs, int defStyle) {
// Initialize paint objects
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
paintBorder.setStyle(Paint.Style.STROKE);
paintSelectorBorder = new Paint();
paintSelectorBorder.setAntiAlias(true);
// Enable software rendering on HoneyComb and up. (needed for shadow)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
setLayerType(LAYER_TYPE_SOFTWARE, null);
// Load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);
// Check for extra features being enabled
hasBorder = attributes.getBoolean(R.styleable.CircularImageView_civ_border, false);
hasSelector = attributes.getBoolean(R.styleable.CircularImageView_civ_selector, false);
shadowEnabled = attributes.getBoolean(R.styleable.CircularImageView_civ_shadow, SHADOW_ENABLED);
// Set border properties, if enabled
if(hasBorder) {
int defaultBorderSize = (int) (2 * context.getResources().getDisplayMetrics().density + 0.5f);
setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_civ_borderWidth, defaultBorderSize));
setBorderColor(attributes.getColor(R.styleable.CircularImageView_civ_borderColor, Color.WHITE));
}
// Set selector properties, if enabled
if(hasSelector) {
int defaultSelectorSize = (int) (2 * context.getResources().getDisplayMetrics().density + 0.5f);
setSelectorColor(attributes.getColor(R.styleable.CircularImageView_civ_selectorColor, Color.TRANSPARENT));
setSelectorStrokeWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_civ_selectorStrokeWidth, defaultSelectorSize));
setSelectorStrokeColor(attributes.getColor(R.styleable.CircularImageView_civ_selectorStrokeColor, Color.BLUE));
}
// Set shadow properties, if enabled
if(shadowEnabled) {
shadowRadius = attributes.getFloat(R.styleable.CircularImageView_civ_shadowRadius, SHADOW_RADIUS);
shadowDx = attributes.getFloat(R.styleable.CircularImageView_civ_shadowDx, SHADOW_DX);
shadowDy = attributes.getFloat(R.styleable.CircularImageView_civ_shadowDy, SHADOW_DY);
shadowColor = attributes.getColor(R.styleable.CircularImageView_civ_shadowColor, SHADOW_COLOR);
setShadowEnabled(true);
}
// We no longer need our attributes TypedArray, give it back to cache
attributes.recycle();
}
/**
* Sets the CircularImageView's border width in pixels.
* #param borderWidth Width in pixels for the border.
*/
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
if(paintBorder != null)
paintBorder.setStrokeWidth(borderWidth);
requestLayout();
invalidate();
}
/**
* Sets the CircularImageView's basic border color.
* #param borderColor The new color (including alpha) to set the border.
*/
public void setBorderColor(int borderColor) {
if (paintBorder != null)
paintBorder.setColor(borderColor);
this.invalidate();
}
/**
* Sets the color of the selector to be draw over the
* CircularImageView. Be sure to provide some opacity.
* #param selectorColor The color (including alpha) to set for the selector overlay.
*/
public void setSelectorColor(int selectorColor) {
this.selectorFilter = new PorterDuffColorFilter(selectorColor, PorterDuff.Mode.SRC_ATOP);
this.invalidate();
}
/**
* Sets the stroke width to be drawn around the CircularImageView
* during click events when the selector is enabled.
* #param selectorStrokeWidth Width in pixels for the selector stroke.
*/
public void setSelectorStrokeWidth(int selectorStrokeWidth) {
this.selectorStrokeWidth = selectorStrokeWidth;
this.requestLayout();
this.invalidate();
}
/**
* Sets the stroke color to be drawn around the CircularImageView
* during click events when the selector is enabled.
* #param selectorStrokeColor The color (including alpha) to set for the selector stroke.
*/
public void setSelectorStrokeColor(int selectorStrokeColor) {
if (paintSelectorBorder != null)
paintSelectorBorder.setColor(selectorStrokeColor);
this.invalidate();
}
/**
* Enables a dark shadow for this CircularImageView.
* #param enabled Set to true to draw a shadow or false to disable it.
*/
public void setShadowEnabled(boolean enabled) {
shadowEnabled = enabled;
updateShadow();
}
/**
* Enables a dark shadow for this CircularImageView.
* If the radius is set to 0, the shadow is removed.
* #param radius Radius for the shadow to extend to.
* #param dx Horizontal shadow offset.
* #param dy Vertical shadow offset.
* #param color The color of the shadow to apply.
*/
public void setShadow(float radius, float dx, float dy, int color) {
shadowRadius = radius;
shadowDx = dx;
shadowDy = dy;
shadowColor = color;
updateShadow();
}
#Override
public void onDraw(Canvas canvas) {
// Don't draw anything without an image
if(image == null)
return;
// Nothing to draw (Empty bounds)
if(image.getHeight() == 0 || image.getWidth() == 0)
return;
// Update shader if canvas size has changed
int oldCanvasSize = canvasSize;
canvasSize = getWidth() < getHeight() ? getWidth() : getHeight();
if(oldCanvasSize != canvasSize)
updateBitmapShader();
// Apply shader to paint
paint.setShader(shader);
// Keep track of selectorStroke/border width
int outerWidth = 0;
// Get the exact X/Y axis of the view
int center = canvasSize / 2;
if(hasSelector && isSelected) { // Draw the selector stroke & apply the selector filter, if applicable
outerWidth = selectorStrokeWidth;
center = (canvasSize - (outerWidth * 2)) / 2;
paint.setColorFilter(selectorFilter);
canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f, paintSelectorBorder);
}
else if(hasBorder) { // If no selector was drawn, draw a border and clear the filter instead... if enabled
outerWidth = borderWidth;
center = (canvasSize - (outerWidth * 2)) / 2;
paint.setColorFilter(null);
RectF rekt = new RectF(0 + outerWidth / 2, 0 + outerWidth / 2, canvasSize - outerWidth / 2, canvasSize - outerWidth / 2);
canvas.drawArc(rekt, 360, 360, false, paintBorder);
//canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2) + outerWidth - 4.0f, paintBorder);
}
else // Clear the color filter if no selector nor border were drawn
paint.setColorFilter(null);
// Draw the circular image itself
canvas.drawCircle(center + outerWidth, center + outerWidth, ((canvasSize - (outerWidth * 2)) / 2), paint);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
// Check for clickable state and do nothing if disabled
if(!this.isClickable()) {
this.isSelected = false;
return super.onTouchEvent(event);
}
// Set selected state based on Motion Event
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
this.isSelected = true;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_SCROLL:
case MotionEvent.ACTION_OUTSIDE:
case MotionEvent.ACTION_CANCEL:
this.isSelected = false;
break;
}
// Redraw image and return super type
this.invalidate();
return super.dispatchTouchEvent(event);
}
#Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
// Extract a Bitmap out of the drawable & set it as the main shader
image = drawableToBitmap(getDrawable());
if(canvasSize > 0)
updateBitmapShader();
}
#Override
public void setImageResource(int resId) {
super.setImageResource(resId);
// Extract a Bitmap out of the drawable & set it as the main shader
image = drawableToBitmap(getDrawable());
if(canvasSize > 0)
updateBitmapShader();
}
#Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
// Extract a Bitmap out of the drawable & set it as the main shader
image = drawableToBitmap(getDrawable());
if(canvasSize > 0)
updateBitmapShader();
}
#Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
// Extract a Bitmap out of the drawable & set it as the main shader
image = bm;
if(canvasSize > 0)
updateBitmapShader();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// The parent has determined an exact size for the child.
result = specSize;
}
else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
}
else {
// The parent has not imposed any constraint on the child.
result = canvasSize;
}
return result;
}
private int measureHeight(int measureSpecHeight) {
int result;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = canvasSize;
}
return (result + 2);
}
// TODO: Update shadow layers based on border/selector state and visibility.
private void updateShadow() {
float radius = shadowEnabled ? shadowRadius : 0;
//paint.setShadowLayer(radius, shadowDx, shadowDy, shadowColor);
paintBorder.setShadowLayer(radius, shadowDx, shadowDy, shadowColor);
paintSelectorBorder.setShadowLayer(radius, shadowDx, shadowDy, shadowColor);
}
/**
* Convert a drawable object into a Bitmap.
* #param drawable Drawable to extract a Bitmap from.
* #return A Bitmap created from the drawable parameter.
*/
public Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) // Don't do anything without a proper drawable
return null;
else if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable
Log.i(TAG, "Bitmap drawable!");
return ((BitmapDrawable) drawable).getBitmap();
}
int intrinsicWidth = drawable.getIntrinsicWidth();
int intrinsicHeight = drawable.getIntrinsicHeight();
if (!(intrinsicWidth > 0 && intrinsicHeight > 0))
return null;
try {
// Create Bitmap object out of the drawable
Bitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError e) {
// Simply return null of failed bitmap creations
Log.e(TAG, "Encountered OutOfMemoryError while generating bitmap!");
return null;
}
}
// TODO TEST REMOVE
public void setIconModeEnabled(boolean e) {}
/**
* Re-initializes the shader texture used to fill in
* the Circle upon drawing.
*/
public void updateBitmapShader() {
if (image == null)
return;
shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
if(canvasSize != image.getWidth() || canvasSize != image.getHeight()) {
Matrix matrix = new Matrix();
float scale = (float) canvasSize / (float) image.getWidth();
matrix.setScale(scale, scale);
shader.setLocalMatrix(matrix);
}
}
/**
* #return Whether or not this view is currently
* in its selected state.
*/
public boolean isSelected() {
return this.isSelected;
}
}
Usage
<com.yourpackage.CircularImageView
android:layout_width="100dp"
android:id="#+id/btn_myprofile"
android:layout_height="100dp"
app:civ_border="true"
app:civ_borderColor="#FF9900"
app:civ_borderWidth="2dp"
app:civ_shadow="false"
android:background="#drawable/profile_icon" />
https://github.com/hdodenhof/CircleImageView
https://github.com/lopspower/CircularImageView

custom circular image view

I am trying to create the circular image view. After searching google I have tried something but its not working.
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
class WheelItemView extends ImageView {
private int _index;
private float _x;
private float _y;
private int _width;
private int _height;
private boolean _drawn;
private float _currentAngle;
private Paint paint;
private Paint paintBorder;
private int borderWidth;
private boolean _hasRotation = false;
private float _dx=0;
private float _dy=0;
private Bitmap image;
private int canvasSize;
public WheelItemView(Context context) {
this(context, null);
}
public WheelItemView(Context context, AttributeSet attrs) {
this(context, attrs, in.eaft.byoo.R.attr.circularImageViewStyle);
// this(context, attrs, 0);
}
public WheelItemView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
// load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs, in.eaft.byoo.R.styleable.CircularImageView, defStyle, 0);
if(attributes.getBoolean(in.eaft.byoo.R.styleable.CircularImageView_border, true)) {
int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics()
.density + 0.5f);
setBorderWidth(attributes.getDimensionPixelOffset(in.eaft.byoo.R.styleable.
CircularImageView_border_width, defaultBorderSize));
setBorderColor(attributes.getColor(in.eaft.byoo.R.styleable.CircularImageView_border_color,
Color.WHITE));
}
if(attributes.getBoolean(in.eaft.byoo.R.styleable.CircularImageView_shadow, true))
addShadow();
}
private void addShadow() {
setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
}
private void setBorderColor(int color) {
if(paintBorder != null)
paintBorder.setColor(color);
this.invalidate();
}
private void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
this.requestLayout();
this.invalidate();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
/*_width= measureWidth(widthMeasureSpec);
_height = measureHeight(heightMeasureSpec);*/
setMeasuredDimension(_width, _height);
}
private int measureHeight(int measureSpecHeight) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = canvasSize;
}
return (result + 2);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// The parent has determined an exact size for the child.
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// The parent has not imposed any constraint on the child.
result = canvasSize;
}
return result;
}
#Override
public void setImageBitmap(Bitmap src)
{
_width = src.getWidth();
_height = src.getHeight();
if(_hasRotation) {
calculateDistance();
}
super.setImageBitmap(src);
}
#Override
protected void onDraw(Canvas canvas)
{
//if(_hasRotation) {
/*Drawable d = getDrawable();
if(d!=null && d instanceof BitmapDrawable && ((BitmapDrawable)d).getBitmap()!=null) {
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
canvas.save();
canvas.translate(_dx, _dy);
canvas.rotate(_currentAngle+90, _width/2f, _height/2f);
// canvas.drawText(text, 0, 0, p);
canvas.drawBitmap(((BitmapDrawable)d).getBitmap(),0, 0, p);
canvas.restore();
return;
}*/
System.out.println("get drawable is null : " + (getDrawable() == null));
image = drawableToBitmap(getDrawable());
// init shader
if (image != null) {
canvasSize = canvas.getWidth();
if(canvas.getHeight()<canvasSize)
canvasSize = canvas.getHeight();
BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize,
canvasSize, false),
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
// circleCenter is the x or y of the view's center
// radius is the radius in pixels of the cirle to be drawn
// paint contains the shader that will texture the shape
int circleCenter = (canvasSize - (borderWidth * 2)) / 2;
canvas.save();
// canvas.translate(_dx, _dy);
canvas.rotate(_currentAngle+90, _width/2f, _height/2f);
canvas.drawCircle(_width-_dx, _height-_dy/2,
borderWidth * 10, paintBorder);
canvas.drawCircle(_width-_dx, _height-_dy/2,
borderWidth * 10, paint);
/*canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth,
((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder);
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth,
((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint);*/
canvas.restore();
// }
}
super.onDraw(canvas);
}
private Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) {
return null;
} else if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(70,
70, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
private void calculateDistance()
{
_dx = (float) ((Math.sqrt(_width*_width + _height*_height)-_width)/2.0f);
_dy = (float) ((Math.sqrt(_width*_width + _height*_height)-_height)/2.0f);
}
public void setIndex(int index)
{
this._index = index;
}
public int getIndex()
{
return _index;
}
public void setCurrentAngle(float currentAngle)
{
this._currentAngle = currentAngle;
}
public float getCurrentAngle()
{
return _currentAngle;
}
public void setAxisX(float x)
{
this._x = x;
}
public float getAxisX()
{
return _x;
}
public void setAxisY(float y)
{
this._y = y;
}
public float getAxisY()
{
return _y;
}
public void setDrawn(boolean drawn)
{
this._drawn = drawn;
}
public boolean isDrawn()
{
return _drawn;
}
public void setItemWidth(int _width)
{
this._width = _width;
}
public float getItemWidth()
{
return _width;
}
public void setItemHeight(int _height)
{
this._height = _height;
}
public float getItemHeight()
{
return _height;
}
public int getDistanceX()
{
return (int)_dx;
}
public int getDistanceY()
{
return (int)_dy;
}
public void setRotatedItem(Boolean flag)
{
_hasRotation = flag;
if(_hasRotation && (_dx==0 || _dy ==0)) {
calculateDistance();
}
if(!_hasRotation) {
_dx = _dy = 0;
}
}
}
My images are not circular.Instead part of circle is being displayed behind the square image.
can anyone tell me what mistake I have done?
I think ur asking for this
jst create a shape in res>drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#a7a7a7" />
<stroke android:width="1dp" android:color="#818181" />
</shape>
and use this shape in ur imageview

how can i show a square image in a circle?

I'm trying to mimic something from the iPhone version of my app. I have a square image and I want to show it in a circle with a white border around it. like this
Is there a way I can do this?
You can achieve this effect, or something very close to it, using a custom Drawable class, containing a Paint object with a BitmapShader that renders the image as a texture. This is the code I'm using (slightly adapted from Romain's Guy post, which uses the same technique to draw images with rounded corners).
class CircularDrawable extends Drawable
{
private float mCircleRadius;
private final RectF mBackgroundRect = new RectF();
private final Paint mBackgroundPaint;
private final BitmapShader mBitmapShader;
private final Paint mPaint;
private final int mMargin;
CircularDrawable(Bitmap bitmap, int margin, int backgroundColor)
{
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(mBitmapShader);
mMargin = margin;
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(backgroundColor);
}
#Override
protected void onBoundsChange(Rect bounds)
{
super.onBoundsChange(bounds);
mBackgroundRect.set(bounds);
mCircleRadius = Math.min(bounds.width() / 2 - mMargin, bounds.height() / 2 - mMargin);
}
#Override
public void draw(Canvas canvas)
{
canvas.drawRect(mBackgroundRect, mBackgroundPaint);
canvas.drawCircle(mBackgroundRect.width() / 2, mBackgroundRect.height() / 2, mCircleRadius, mPaint);
}
#Override
public int getOpacity()
{
return PixelFormat.TRANSLUCENT;
}
#Override
public void setAlpha(int alpha)
{
mPaint.setAlpha(alpha);
mBackgroundPaint.setAlpha(alpha);
}
#Override
public void setColorFilter(ColorFilter cf)
{
mPaint.setColorFilter(cf);
mBackgroundPaint.setColorFilter(cf);
}
}
Having the bitmap you want to draw, just build a CircularDrawable from it with
new CircularDrawable(bitmap, margin, Color.WHITE);
Try this.
public class CircularImageView extends ImageView {
private int borderWidth;
private int viewWidth;
private int viewHeight;
private Bitmap image;
private Paint paint;
private Paint paintBorder;
private BitmapShader shader;
public CircularImageView(final Context context) {
this(context, null);
}
public CircularImageView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.circularImageViewStyle);
}
public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// init paint
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
// load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs,
R.styleable.CircularImageView, defStyle, 0);
if (attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
setBorderWidth(attributes.getColor(
R.styleable.CircularImageView_border_width, 4));
setBorderColor(attributes.getInt(
R.styleable.CircularImageView_border_color, Color.WHITE));
}
if (attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
addShadow();
}
public void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
this.invalidate();
}
public void setBorderColor(int borderColor) {
if (paintBorder != null)
paintBorder.setColor(borderColor);
this.invalidate();
}
public void addShadow() {
setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
}
#SuppressLint("DrawAllocation")
#Override
public void onDraw(Canvas canvas) {
// load the bitmap
BitmapDrawable bitmapDrawable = (BitmapDrawable) this.getDrawable();
if (bitmapDrawable != null)
image = bitmapDrawable.getBitmap();
// init shader
if (image != null) {
shader = new BitmapShader(Bitmap.createScaledBitmap(image,
canvas.getWidth(), canvas.getHeight(), false),
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
int circleCenter = viewWidth / 2;
// circleCenter is the x or y of the view's center
// radius is the radius in pixels of the cirle to be drawn
// paint contains the shader that will texture the shape
canvas.drawCircle(circleCenter + borderWidth, circleCenter
+ borderWidth, circleCenter + borderWidth - 4.0f,
paintBorder);
canvas.drawCircle(circleCenter + borderWidth, circleCenter
+ borderWidth, circleCenter - 4.0f, paint);
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec, widthMeasureSpec);
viewWidth = width - (borderWidth * 2);
viewHeight = height - (borderWidth * 2);
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = viewWidth;
}
return result;
}
private int measureHeight(int measureSpecHeight, int measureSpecWidth) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = viewHeight;
}
return (result + 2);
}
}
I'd make a custom view and just draw what you want to the canvas- draw the border, then the white circle, then the image.It's a couple of easy canvas calls. If you need to clip the image to a circular area, just set a clipping Region before doing the image draw.

Categories

Resources