Android Progressbar with circle radius changes Dynamically - android

I want to change the circle radius dependent on the slider position
I created both individually.
while apply the circle method to the the Progress bar.
facing error.
Actually I call the Progress-Bar(Seek Bar) with
setContentView(R.layout.main);
and for drawing circle as you know I have to used setContentView(demoview);
Query: I want to merge both layout as display into image.
I didn't have idea will it possible or not?
Any guidance,tutorial appreciable.
Thanks for give your valuable time for my query.
Hope you have solution.

Check this out..
I am not using android seekbar, instead i am drawing a similar seekbar on canvas..
Check if this code can help u..
package com.test;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class SampleComp extends View implements OnTouchListener {
private Paint paint = null;
private int width = 0;
private int height = 0;
private int barStartX = 20;
private int barStartY = 20;
private int barEndX;
private int barEndY = 30;
private int radius;
private int heightAvailableForCircle;
private int widthAvailableForCircle;
private int maxRadius;
private int totalSeekBarLength;
private int currentSeekBarLength = 10;
private int whatPercentOfSeekBarIsSelected = 50;
public SampleComp(Context context) {
super(context);
paint = new Paint();
paint.setAntiAlias(true);
setOnTouchListener(this);
}
public SampleComp(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint.setAntiAlias(true);
}
public SampleComp(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
paint.setAntiAlias(true);
}
#Override
public void onDraw(Canvas canvas){
barEndX = getWidth() - 20;
paint.setColor(Color.WHITE);
setWidth(canvas.getWidth());
setHeight(canvas.getHeight());
setHeightAvailableForCircle(getViewHeight() - barEndY);
setWidthAvailableForCircle(getViewWidth() - 40);
System.out.println("heightAvailableForCircle: "+getAvailableHeightForCircle());
System.out.println("widthAvailableForCircle: "+getWidthAvailableForCircle());
totalSeekBarLength = barEndX - barStartX;
System.out.println("SEEK LEN: "+totalSeekBarLength);
canvas.drawRect(barStartX, barStartY, barEndX, barEndY, paint);
paint.setColor(Color.BLUE);
setMaxRadius(heightAvailableForCircle, widthAvailableForCircle);
whatPercentOfSeekBarIsSelected = getSelectedSeekBarPercentage(totalSeekBarLength,getCurrentSeekBarLenghtSelected());
System.out.println("whatPercentOfSeekBarIsSelected: "+whatPercentOfSeekBarIsSelected);
System.out.println("!!!!!: "+canvas.getWidth());
System.out.println("####: "+getViewWidth());
System.out.println("^^^^^^^^^************: "+ (whatPercentOfSeekBarIsSelected * (getViewWidth() - 40)) / 100);
canvas.drawRect(barStartX, barStartY, ( (whatPercentOfSeekBarIsSelected * (getViewWidth() - 40)) / 100) + 20,
barEndY, paint);
paint.setColor(Color.GRAY);
setRadius(whatPercentOfSeekBarIsSelected);
canvas.drawCircle( (canvas.getWidth())/2, (canvas.getHeight() - 30)/2, radius, paint);
}
private void setRadius(int per){
this.radius = (getMaxRadius() * per)/100;
}
private int getSelectedSeekBarPercentage(int total, int current){
int per = 0;
per = ( (current * 100) / total);
return per;
}
private void setRadius(int total, int current){
System.out.println("total: "+total);
System.out.println("current: "+current);
this.radius = ( ( (getMaxRadius()/2) * current) / 100);
System.out.println("radius: "+this.radius);
}
private void setMaxRadius(int h, int w){
this.maxRadius = h < w ? h/2 : w/2 ;
}
private int getMaxRadius(){
return this.maxRadius;
}
private void setWidth(int w){
this.width = w;
}
private void setHeight(int h){
this.height = h;
}
private int getViewWidth(){
return this.width;
}
private int getViewHeight() {
return this.height;
}
private void setHeightAvailableForCircle(int availableHeightForCircle){
this.heightAvailableForCircle = availableHeightForCircle;
}
private int getAvailableHeightForCircle(){
return this.heightAvailableForCircle;
}
private void setWidthAvailableForCircle(int wid){
this.widthAvailableForCircle = wid;
}
private int getWidthAvailableForCircle(){
return this.widthAvailableForCircle;
}
private void setCurrentSeekBarLength(int x){
this.currentSeekBarLength = x;
}
private int getCurrentSeekBarLenghtSelected(){
return this.currentSeekBarLength;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
System.out.println("x: "+x);
System.out.println("y: "+y);
if(x >= 10 && x<= barEndX && y >= 10 && y <= 30){
System.out.println("TRUE");
setCurrentSeekBarLength(x - 20);
invalidate();
}
return false;
}
}
And this is my Activity class:
package com.test;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;
public class SampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleComp(this));
}
}

Can u be little more specific regarding what u want to achieve. Ur question isn't that clear. What i can make out is, u want to increase/decrease the radius of the circle based on the progress bar value.

Have a look at the android custom component guide. You basically have to derive your circle component from android.view.View. Then you can add it to your layout like every other component.

Related

Reload a layout in android, update circle progress bar programmatically

I'm using this library from GitHub: https://github.com/lzyzsd/CircleProgress
I put ArcProgress into my MainLayout. I'm trying to change values on the progress bar but I cannot not see on screen. If I check with mArcProgress.getProgress(); this get me the right value, but the bar is empty in screen and doesn't show any progress.
I was trying using:
mArcProgress.invalidate();
but doesnt work.
The only way I found was with:
finish();
startActivity(getIntent());
but works not as I expected, because the full screen start and seems like a blink.
Anyone know how from another activity, changes this View and make possible to see the changes when setting mArcProgress.setProgress(aNumber); ?
this is ArcProgressFuel
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class ArcProgressFuel extends View {
private Paint paint;
private RectF rectF = new RectF();
private float strokeWidth;
public int progress;
private int max;
private int finishedStrokeColor;
private int unfinishedStrokeColor;
private float arcAngle;
Path path;
MainPageFragment mMainPageFragment;
public static int fuel_to_show;
private float arcBottomHeight;
private final int default_finished_color = Color.WHITE;
private final int default_unfinished_color = Color.rgb(72, 106, 176);
private final float default_suffix_padding;
private final float default_stroke_width;
private final int default_max = 100;
private final float default_arc_angle = 360 * 0.5f; //0.8 for speed, 0.5 for fuel
private float default_text_size;
private final int min_size;
private static final String INSTANCE_STATE = "saved_instance";
private static final String INSTANCE_STROKE_WIDTH = "stroke_width";
public static String instance_progress = "progress";
private static final String INSTANCE_MAX = "max";
private static final String INSTANCE_FINISHED_STROKE_COLOR = "finished_stroke_color";
private static final String INSTANCE_UNFINISHED_STROKE_COLOR = "unfinished_stroke_color";
private static final String INSTANCE_ARC_ANGLE = "arc_angle";
private static final String INSTANCE_SUFFIX = "suffix";
public ArcProgressFuel(Context context) {
this(context, null);
}
public ArcProgressFuel(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ArcProgressFuel(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
min_size = (int) Utils.dp2px(getResources(), 100);
default_suffix_padding = Utils.dp2px(getResources(), 4);
default_stroke_width = Utils.dp2px(getResources(), 4);
TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ArcProgress, defStyleAttr, 0);
initByAttributes(attributes);
attributes.recycle();
initPainters();
}
protected void initByAttributes(TypedArray attributes) {
finishedStrokeColor = attributes.getColor(R.styleable.ArcProgress_arc_finished_color, default_finished_color);
unfinishedStrokeColor = attributes.getColor(R.styleable.ArcProgress_arc_unfinished_color, default_unfinished_color);
arcAngle = attributes.getFloat(R.styleable.ArcProgress_arc_angle, default_arc_angle);
setMax(attributes.getInt(R.styleable.ArcProgress_arc_max, default_max));
setProgress(attributes.getInt(R.styleable.ArcProgress_arc_progress, 0));
strokeWidth = attributes.getDimension(R.styleable.ArcProgress_arc_stroke_width, default_stroke_width);
fuel_to_show=mMainPageFragment.carFuel;
setProgress(fuel_to_show); //Aca puedo modificar el valor
}
protected void initPainters() {
paint = new Paint();
paint.setColor(default_unfinished_color);
paint.setAntiAlias(true);
paint.setStrokeWidth(strokeWidth);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
}
/* #Override
public void invalidate() {
initPainters();
super.invalidate();
postInvalidate();
}*/
public float getStrokeWidth() {
return strokeWidth;
}
public void setStrokeWidth(float strokeWidth) {
this.strokeWidth = strokeWidth;
this.invalidate();
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
if (this.progress > getMax()) {
this.progress %= getMax();
}
invalidate();
}
public int getMax() {
return max;
}
public void setMax(int max) {
if (max > 0) {
this.max = max;
invalidate();
}
}
public int getFinishedStrokeColor() {
return finishedStrokeColor;
}
public void setFinishedStrokeColor(int finishedStrokeColor) {
this.finishedStrokeColor = finishedStrokeColor;
this.invalidate();
}
public int getUnfinishedStrokeColor() {
return unfinishedStrokeColor;
}
public void setUnfinishedStrokeColor(int unfinishedStrokeColor) {
this.unfinishedStrokeColor = unfinishedStrokeColor;
this.invalidate();
}
public float getArcAngle() {
return arcAngle;
}
public void setArcAngle(float arcAngle) {
this.arcAngle = arcAngle;
this.invalidate();
}
#Override
protected int getSuggestedMinimumHeight() {
return min_size;
}
#Override
protected int getSuggestedMinimumWidth() {
return min_size;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
rectF.set(strokeWidth / 2f, strokeWidth / 2f, width - strokeWidth / 2f, MeasureSpec.getSize(heightMeasureSpec) - strokeWidth / 2f);
float radius = width / 2f;
float angle = (360 - arcAngle) / 2f;
arcBottomHeight = radius * (float) (1 - Math.cos(angle / 180 * Math.PI));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float startAngle = 90 - arcAngle / 2f; //270 for speed, 90 for fuel
float finishedSweepAngle = progress / (float) getMax() * arcAngle;
float finishedStartAngle = startAngle;
if(progress == 0) finishedStartAngle = 0.01f;
paint.setColor(unfinishedStrokeColor);
canvas.drawArc(rectF, startAngle, arcAngle, false, paint);
paint.setColor(finishedStrokeColor);
canvas.drawArc(rectF, finishedStartAngle, finishedSweepAngle, false, paint);
if(arcBottomHeight == 0) {
float radius = getWidth() / 2f;
float angle = (360 - arcAngle) / 2f;
arcBottomHeight = radius * (float) (1 - Math.cos(angle / 180 * Math.PI));
}
}
#Override
protected Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
bundle.putFloat(INSTANCE_STROKE_WIDTH, getStrokeWidth());
bundle.putInt(instance_progress, getProgress());
bundle.putInt(INSTANCE_MAX, getMax());
bundle.putInt(INSTANCE_FINISHED_STROKE_COLOR, getFinishedStrokeColor());
bundle.putInt(INSTANCE_UNFINISHED_STROKE_COLOR, getUnfinishedStrokeColor());
bundle.putFloat(INSTANCE_ARC_ANGLE, getArcAngle());
return bundle;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
if(state instanceof Bundle) {
final Bundle bundle = (Bundle) state;
strokeWidth = bundle.getFloat(INSTANCE_STROKE_WIDTH);
setMax(bundle.getInt(INSTANCE_MAX));
setProgress(bundle.getInt(instance_progress));
finishedStrokeColor = bundle.getInt(INSTANCE_FINISHED_STROKE_COLOR);
unfinishedStrokeColor = bundle.getInt(INSTANCE_UNFINISHED_STROKE_COLOR);
initPainters();
super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));
return;
}
super.onRestoreInstanceState(state);
}
}
this is inside my MainLayout, this part I want to update:
<RelativeLayout
android:id="#+id/scale_gaz_inmain"
android:layout_width="#dimen/_57sdp"
android:layout_centerHorizontal="true"
android:layout_below="#+id/icon_gazinmain"
android:layout_height="#dimen/_60sdp"
>
<com.itelma.tele2.ArcProgressFuel
android:id="#+id/arc_progress2"
android:background="#android:color/transparent"
android:layout_width="match_parent"
android:scaleX="-1"
android:layout_height="match_parent"
custom:arc_progress="50"
custom:arc_unfinished_color="#color/mDark_gray"
custom:arc_finished_color="#color/colorApp"
custom:arc_max="100"/>
</RelativeLayout>
so in my main java file I have:
ArcProgressFuel mArcProgressFuel;
mArcProgressFuel=new ArcProgressFuel(this);
mArcProgressFuel.invalidate();
ok, I could resove it, with the following lines:
mArcProgressFuel=new ArcProgressFuel(this);
RelativeLayout relativeLayout2=(RelativeLayout)findViewById(R.id.speed_indicator);
View child = getLayoutInflater().inflate(R.layout.fragment_speed_indicator, null);
relativeLayout2.addView(child);

How to make a square shape generate in an Android app instead of a circle

I am working on a android launcher that shows the 1st 4 app icons in a grid view however I'm trying to display the folder as a square shape it's showing up as a circle shape...
heres my code:
package appname.launcher.util;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import Appname.launcher.activity.Home;
public class GroupIconDrawable extends Drawable{
private int outlinepad;
Bitmap[] icons;
public int iconSize;
Paint paint;
Paint paint2;
Paint paint4;
private int iconSizeDiv2;
private int padding;
private float scaleFactor = 1;
private boolean needAnimate,needAnimatScale;
public View v;
private float sx = 1;
private float sy = 1 ;
public GroupIconDrawable(Bitmap[] icons,int size){
init(icons,size);
}
private void init(Bitmap[] icons,int size){
this.icons = icons;
this.iconSize = size;
iconSizeDiv2 = Math.round(iconSize / 2f);
padding = iconSize /25;
this.paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAlpha(200);
paint.setAntiAlias(true);
this.paint4 = new Paint();
paint4.setColor(Color.WHITE);
paint4.setAntiAlias(true);
paint4.setFlags(Paint.ANTI_ALIAS_FLAG);
paint4.setStyle(Paint.Style.STROKE);
outlinepad = Tools.convertDpToPixel(2, Home.desktop.getContext());
paint4.setStrokeWidth(outlinepad);
this.paint2 = new Paint();
paint2.setAntiAlias(true);
paint2.setFilterBitmap(true);
}
public GroupIconDrawable(Bitmap[] icons,int size,View v){
init(icons,size);
this.v =v;
}
public void popUp(){
sy = 1;
sx = 1;
needAnimate = true;
needAnimatScale = true;
invalidateSelf();
}
public void popBack(){
needAnimate = false;
needAnimatScale = false;
invalidateSelf();
}
#Override
public void draw(Canvas canvas) {
canvas.save();
if (needAnimatScale){
scaleFactor = Tools.clampFloat(scaleFactor-0.09f,0.5f,1f);
}else {
scaleFactor = Tools.clampFloat(scaleFactor+0.09f,0.5f,1f);
}
if (v == null)
canvas.scale(scaleFactor,scaleFactor,iconSize/2,iconSize/2);
else
canvas.scale(scaleFactor,scaleFactor,iconSize/2,v.getHeight() / 2);
if (v!= null)
canvas.translate(0,v.getHeight()/2-iconSize/2);
Path clipp = new Path();
clipp.addCircle(iconSize / 2,iconSize / 2,iconSize / 2-outlinepad, Path.Direction.CW);
canvas.clipPath(clipp, Region.Op.REPLACE);
canvas.drawBitmap(icons[0],null,new Rect(padding,padding, iconSizeDiv2-padding, iconSizeDiv2-padding),paint2);
canvas.drawBitmap(icons[1],null,new Rect(iconSizeDiv2+padding,padding,iconSize-padding, iconSizeDiv2-padding),paint2);
canvas.drawBitmap(icons[2],null,new Rect(padding, iconSizeDiv2+padding, iconSizeDiv2-padding,iconSize-padding),paint2);
canvas.drawBitmap(icons[3],null,new Rect(iconSizeDiv2+padding, iconSizeDiv2+padding,iconSize-padding,iconSize-padding),paint2);
canvas.clipRect(0,0,iconSize,iconSize, Region.Op.REPLACE);
canvas.restore();
if (needAnimate){
paint2.setAlpha(Tools.clampInt(paint2.getAlpha()-25,0,255));
invalidateSelf();
}else if (paint2.getAlpha() != 255){
paint2.setAlpha(Tools.clampInt(paint2.getAlpha()+25,0,255));
invalidateSelf();
}
}
#Override
public void setAlpha(int i) {}
#Override
public void setColorFilter(ColorFilter colorFilter) {}
#Override
public int getOpacity() {return 0;}
}
I think its because of the > clipp.addCircle(iconSize / 2,iconSize /
2,iconSize / 2-outlinepad,> Path.Direction.CW); code but i'm not sure
how would I make it a square instead of a circle?
change your clipp Path usage from addCircle to be addRect(float left, float top, float right, float bottom, Path.Direction dir)

Set seekbar thumb above seekbar line

In my Android app, I have to customize a seekbar and I wonder how I can set a seekbar thumb above its progress line instead of center by default?
You can check it out Discrete Seekbar
seekBar.setMin(0);
seekBar.setMax(yourArray.length);
seekBar.setOnProgressChangeListener(new DiscreteSeekBar.OnProgressChangeListener() {
int onProgressChanged =0;
#Override
public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {
onProgressChanged = value;
}
#Override
public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
}
});
I looked for this info in many posts and get some ideas from there and here, and created SeekBayHint, which creates text of progress above arrow:
SeekBar
MainClass:
package your_package;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import your_package.R;
public class SeekBarHint extends android.support.v7.widget.AppCompatSeekBar {
private Paint mTextPaint;
private Rect mTextBounds = new Rect();
private Bitmap mBitmapIconArrowDown;
/** for this class yPosition must be as minHeight in layoutFile for this seekBar*/
private static int sTextYPositionIndent = 20;
private float mTextSizeDecrease = 1.75f;
public static void setTextYPositionIndent(int textYPositionIndent) {
sTextYPositionIndent = textYPositionIndent;
}
public SeekBarHint(Context context) {
super(context);
mBitmapIconArrowDown = BitmapFactory.decodeResource(context.getResources(),
R.drawable.progress_seek_bar_arrow_down);
mTextPaint = new Paint();
mTextPaint.setColor(getResources().getColor(R.color.colorPrimary));
}
public SeekBarHint(Context context, AttributeSet attrs) {
super(context, attrs);
mBitmapIconArrowDown = BitmapFactory.decodeResource(context.getResources(),
R.drawable.progress_seek_bar_arrow_down);
mTextPaint = new Paint();
mTextPaint.setColor(getResources().getColor(R.color.colorPrimary));
}
public SeekBarHint(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mBitmapIconArrowDown = BitmapFactory.decodeResource(context.getResources(),
R.drawable.progress_seek_bar_arrow_down);
mTextPaint = new Paint();
mTextPaint.setColor(getResources().getColor(R.color.colorPrimary));
}
#Override
protected synchronized void onDraw(Canvas canvas) {
// first draw the regular progress bar, then custom draw our textString
super.onDraw(canvas);
// now progress position and convert to textString.
String textString = Integer.toString(getProgress()) + "%";
// now get size of seek bar.
float width = getWidth();
float height = getHeight();
// set textString size.
mTextPaint.setTextSize(height / mTextSizeDecrease);
// get size of textString.
mTextPaint.getTextBounds(textString, 0, textString.length(), mTextBounds);
// calculate where to start printing textString.
float position = (width / getMax()) * getProgress();
// get start and end points of where textString will be printed.
float textXStart = position - mTextBounds.centerX();
float textXEnd = position + mTextBounds.centerX();
// check does not start drawing text outside seek bar.
if (textXStart < 0)
textXStart = 0;
if (textXEnd > width)
textXStart -= (textXEnd - width);
// calculate y textString print position.
float yPosition = (height / 2) - mTextBounds.centerY();
canvas.drawText(textString, textXStart, yPosition - sTextYPositionIndent, mTextPaint);
// arrow draw logic
// check does not start drawing arrow outside seek bar
int seekBarAbsoluteWidth = getWidth() - getPaddingLeft() - getPaddingRight();
int thumbPos = (getPaddingLeft() / 2) + (seekBarAbsoluteWidth * getProgress() / getMax());
// set height and width for new bitmap
int arrowHeight = Math.round(mTextBounds.height()/2f);
int arrowWidth = mTextBounds.width()/3;
Bitmap scaledBitmapIconArrowDown = Bitmap
.createScaledBitmap(mBitmapIconArrowDown, arrowWidth, arrowHeight, true);
canvas.drawBitmap(scaledBitmapIconArrowDown, thumbPos, yPosition, null);
}
}
To support different dimension use this code in OnCreateView (if seekBar used in fragment) or in OnCreate (if seekBar used in activity):
DisplayMetrics metrics = getResources().getDisplayMetrics();
int dpi = metrics.densityDpi;
if(dpi < 230){
SeekBarHint.setTextYPositionIndent(5);
} else if (dpi < 310){
SeekBarHint.setTextYPositionIndent(15);
} else if (dpi < 470){
SeekBarHint.setTextYPositionIndent(10);
}

Android Application runs but nothing is drawn on canvas

I wrote a Compass example that came out of an Android application tutorial book and wrote the custom view, methods, and such, but nothing is being drawn on the screen when the app runs.
Here is the class:
package com.example.compass;
import android.view.View;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
public class CompassView extends View {
private float bearing;
private Paint markerPaint;
private Paint textPaint;
private Paint circlePaint;
private String northString;
private String eastString;
private String southString;
private String westString;
private int textHeight;
public CompassView(Context context) {
super(context);
initCompassView();
}
public CompassView(Context context, AttributeSet attrs) {
super(context, attrs);
initCompassView();
}
public CompassView(Context context, AttributeSet ats, int defaultStyle) {
super(context, ats, defaultStyle);
initCompassView();
}
protected void initCompassView() {
setFocusable(true);
Resources r = this.getResources();
circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
circlePaint.setColor(r.getColor(R.color.background_color));
circlePaint.setStrokeWidth(1);
circlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
northString = r.getString(R.string.cardinal_north);
eastString = r.getString(R.string.cardinal_east);
southString = r.getString(R.string.cardinal_south);
westString = r.getString(R.string.cardinal_west);
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(r.getColor(R.color.text_color));
textHeight = (int)textPaint.measureText("yY");
markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
markerPaint.setColor(r.getColor(R.color.marker_color));
}
#Override
protected void onDraw(Canvas canvas) {
int mMeasuredWidth = getMeasuredWidth();
int mMeasuredHeight = getMeasuredHeight();
int px = mMeasuredWidth/2;
int py = mMeasuredHeight/2;
int radius = Math.min(px, py);
canvas.drawCircle(px, py, radius, circlePaint);
canvas.save();
canvas.rotate(-bearing, px, py);
int textWidth = (int) textPaint.measureText("W");
int cardinalX = px-textWidth/2;
int cardinalY = py-radius+textHeight;
for (int i = 0; i < 24; i++) {
canvas.drawLine(px, py-radius, px, py-radius+10, markerPaint);
canvas.save();
canvas.translate(0, textWidth);
if (i%6 == 0) {
String dirString = "";
switch (i) {
case(0):{
dirString = northString;
int arrowY = 2*textHeight;
canvas.drawLine(px, arrowY, px-5, 3*textHeight, markerPaint);
canvas.drawLine(px, arrowY, px+5, 3*textHeight, markerPaint);
break;
}
case(6): dirString = eastString; break;
case(12): dirString = southString; break;
case(18): dirString = westString; break;
}
canvas.drawText(dirString, cardinalX, cardinalY, textPaint);
}
else if (i%3==0) {
String angle = String.valueOf(i*15);
float angleTextWidth = textPaint.measureText(angle);
int angleTextX = (int)(px-angleTextWidth/2);
int angleTextY = py-radius+textHeight;
canvas.drawText(angle, angleTextX, angleTextY, textPaint);
}
canvas.restore();
canvas.rotate(15, px, py);
}
canvas.restore();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredWidth = measure(widthMeasureSpec);
int measuredHeight = measure(heightMeasureSpec);
int d = Math.min(measuredWidth, measuredHeight);
setMeasuredDimension(d, d);
}
private int measure(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getMode(measureSpec);
if (specMode == MeasureSpec.UNSPECIFIED) {
result = 200;
}
else {
result = specSize;
}
return result;
}
public void setBearing(float _bearing) {
bearing = _bearing;
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
}
public float getBearing() {
return bearing;
}
#SuppressWarnings("deprecation")
#Override
public boolean dispatchPopulateAccessibilityEvent(final AccessibilityEvent event) {
super.dispatchPopulateAccessibilityEvent(event);
if (isShown()) {
String bearingStr = String.valueOf(bearing);
if (bearingStr.length() > AccessibilityEvent.MAX_TEXT_LENGTH)
bearingStr = bearingStr.substring(0, AccessibilityEvent.MAX_TEXT_LENGTH);
event.getText().add(bearingStr);
return true;
}
else
return false;
}
}
I don't get any logcat errors; it does however display this (which might be relevant):
04-01 18:41:57.163: D/gralloc_goldfish(583): Emulator without GPU emulation detected.
However, after seeing this I added GPU emulation hardware to my emulator and selected the "Yes" option, but this message keeps showing up.
What could be the cause of nothing displaying on the screen? I can also post xml files if needed.
Figured out the cause: called getMode a second time instead of getSize... I feel dumb now.

Highlight/select a region in a bitmap

I am trying to be able to select/highlight a specific grid position onTouch.
Basically, I have an image, with a canvas/bitmap over layering the top of the image, I want to be able to click on a point of the image, and have that box become highlighted(first step is highlighting the grid, I will perform other algorithms on this later on)..
Here is the code for what I have now.. I am able to grab the x y coordinates, but I do not know how to associate the x y coordinates with the grid position.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
public class ImageWithGridView extends View {
private int rows = 12;
private int columns = 12;
private float width;
private float height;
public static final String TAG="ImageWithGridView";
private static final String SELX = "selX";
private static final String SELY = "selY";
private static final String VIEW_STATE = "viewState";
//private static final int ID = 92;
private int selX; //X index of selection
private int selY; //Y index of selection
private final Bitmap bitmap;
public ImageWithGridView(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
//use your own image file name, instead of mobot_spring
}
public ImageWithGridView(Context context, AttributeSet attrs){
super(context, attrs);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
//TODO Auto-generated constructor sub
}
public ImageWithGridView(Context context, AttributeSet attrs, int defStyle) {
super (context, attrs, defStyle);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
//TODO Auto-generated constructor stub
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable p = super.onSaveInstanceState();
Log.d(TAG, "onSaveInstanceState");
Bundle bundle = new Bundle();
bundle.putInt(SELX, selY);
bundle.putInt(SELY, selY);
bundle.putParcelable(VIEW_STATE, p);
return bundle;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
Log.d(TAG, "onRestoreInstanceState");
Bundle bundle = (Bundle) state;
selX = bundle.getInt(SELX);
selY = bundle.getInt(SELY);
super.onRestoreInstanceState(bundle.getParcelable(VIEW_STATE));
return;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
//adjust the ratio for width and height here:
this.setMeasuredDimension(parentWidth, parentHeight*2/3);
}
#Override
protected void onSizeChanged(int newWidth, int newHeight, int oldw, int oldh) {
width = newWidth / (float) columns;
height = newHeight / (float)rows;
Log.d(TAG, "~~~~~~~~~~~onSizeChanged: width " + width + ", height " + height);
super.onSizeChanged(newWidth, newWidth, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
RectF dst = new RectF(width, height, (columns-1) * width, (rows - 1) * height);
//Draw the background...
Paint background = new Paint();
background.setColor(getResources().getColor(R.color.background));
Log.d(TAG, "~~~~~~~~~10 ");
canvas.drawRect(0, 0, getWidth(), getHeight(), background);
Log.d(TAG, "~~~~~~~~~20 ");
canvas.drawBitmap(bitmap, null, dst, null);
Log.d(TAG, "~~~~~~~~~30 ");
//Define colors for the grid lines
Paint dark = new Paint();
dark.setColor(getResources().getColor(R.color.dark));
Paint hilite = new Paint();
hilite.setColor(getResources().getColor(R.color.hilite));
Paint light = new Paint();
light.setColor(getResources().getColor(R.color.light));
//Draw the minor grid lines
for (int i = 0; i < rows; i++) {
canvas.drawLine(0, i * height-1, getWidth(), i * height-1, dark);
canvas.drawLine(0, i * height, getWidth(), i * height, light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1, hilite);
}
for (int i=0; i<columns; i++) {
canvas.drawLine(i * width-1, 0, i* width-1, getHeight(), dark);
canvas.drawLine(i * width, 0, i * width, getHeight(), light);
canvas.drawLine(i * width + 1, 0, i* width + 1, getHeight(), hilite);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_DOWN){
return super.onTouchEvent(event);
}
selX = (int) event.getX();
selY = (int) event.getY();
Log.d(TAG, "onTouchEvent: x " + selX + ", y " + selY);
return true;
}
public int getClickedX() {return selX;}
public int getClickedY() {return selY;}
}
This is my other class
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CustomizeImageViewActivity extends Activity{
/** Called when the activity is first created. */
private Button btnShow;
private TextView label;
private ImageWithGridView imgView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setContentView(R.layout.relative_layout);
//setContentView(R.layout.table_layout);
btnShow = (Button) findViewById(R.id.btnShow);
label = (TextView) findViewById(R.id.label);
imgView = (ImageWithGridView)findViewById(R.id.imageView1);
btnShow.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
label.setText("("+imgView.getClickedX() + "," + imgView.getClickedY() + ")");
}
});
}
}
Please advise with any guides/tutorials I should look at.. I have tried doing some research but I have not been able to find anything on this.

Categories

Resources