How to make animation like radar signal in android? [closed] - android

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have an app in which I have to make an animation similar to that of a radar signal. But I am not quite sure of how to accomplish this. Any suggestions in this regard will be appreciated
Example of image like animation

The answer is already given here at this so post see here given by Ajay Pandya
You can use some below libraries
https://github.com/jfabrix101/RadarCustomVIew
https://github.com/gpfduoduo/RadarScanView
i.e
Radar.java
public class RadarView extends View {
private final String LOG = "RadarView";
private final int POINT_ARRAY_SIZE = 25;
private int fps = 100;
private boolean showCircles = true;
float alpha = 0;
Point latestPoint[] = new Point[POINT_ARRAY_SIZE];
Paint latestPaint[] = new Paint[POINT_ARRAY_SIZE];
public RadarView(Context context) {
this(context, null);
}
public RadarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RadarView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Paint localPaint = new Paint();
localPaint.setColor(Color.GREEN);
localPaint.setAntiAlias(true);
localPaint.setStyle(Paint.Style.STROKE);
localPaint.setStrokeWidth(1.0F);
localPaint.setAlpha(0);
int alpha_step = 255 / POINT_ARRAY_SIZE;
for (int i=0; i < latestPaint.length; i++) {
latestPaint[i] = new Paint(localPaint);
latestPaint[i].setAlpha(255 - (i* alpha_step));
}
}
android.os.Handler mHandler = new android.os.Handler();
Runnable mTick = new Runnable() {
#Override
public void run() {
invalidate();
mHandler.postDelayed(this, 1000 / fps);
}
};
public void startAnimation() {
mHandler.removeCallbacks(mTick);
mHandler.post(mTick);
}
public void stopAnimation() {
mHandler.removeCallbacks(mTick);
}
public void setFrameRate(int fps) { this.fps = fps; }
public int getFrameRate() { return this.fps; };
public void setShowCircles(boolean showCircles) { this.showCircles = showCircles; }
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int r = Math.min(width, height);
//canvas.drawRect(0, 0, getWidth(), getHeight(), localPaint);
int i = r / 2;
int j = i - 1;
Paint localPaint = latestPaint[0]; // GREEN
if (showCircles) {
canvas.drawCircle(i, i, j, localPaint);
canvas.drawCircle(i, i, j, localPaint);
canvas.drawCircle(i, i, j * 3 / 4, localPaint);
canvas.drawCircle(i, i, j >> 1, localPaint);
canvas.drawCircle(i, i, j >> 2, localPaint);
}
alpha -= 0.5;
if (alpha < -360) alpha = 0;
double angle = Math.toRadians(alpha);
int offsetX = (int) (i + (float)(i * Math.cos(angle)));
int offsetY = (int) (i - (float)(i * Math.sin(angle)));
latestPoint[0]= new Point(offsetX, offsetY);
for (int x=POINT_ARRAY_SIZE-1; x > 0; x--) {
latestPoint[x] = latestPoint[x-1];
}
int lines = 0;
for (int x = 0; x < POINT_ARRAY_SIZE; x++) {
Point point = latestPoint[x];
if (point != null) {
canvas.drawLine(i, i, point.x, point.y, latestPaint[x]);
}
}
lines = 0;
for (Point p : latestPoint) if (p != null) lines++;
boolean debug = false;
if (debug) {
StringBuilder sb = new StringBuilder(" >> ");
for (Point p : latestPoint) {
if (p != null) sb.append(" (" + p.x + "x" + p.y + ")");
}
Log.d(LOG, sb.toString());
// " - R:" + r + ", i=" + i +
// " - Size: " + width + "x" + height +
// " - Angle: " + angle +
// " - Offset: " + offsetX + "," + offsetY);
}
}
}
in your activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/black">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start"
android:onClick="startAniamtion"/>
<frusso.radartest.RadarView
android:id="#+id/radarView"
android:layout_width="240dp"
android:layout_height="240dp"
android:layout_gravity="center_horizontal"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop"
android:onClick="stopAnimation"/>
Activity.java
public class MainActivity extends Activity {
RadarView mRadarView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRadarView = (RadarView) findViewById(R.id.radarView);
mRadarView.setShowCircles(true);
}
public void stopAnimation(View view) {
if (mRadarView != null) mRadarView.stopAnimation();
}
public void startAnimation(View view) {
if (mRadarView != null) mRadarView.startAnimation();
}
}

Related

How to correctly setColor in a custom view

I have created a custom view like a crop view which is used in my app to define the cropping area. But the app crashes while inflating the view. May be I have not understood how to use the setColor correctly. I have tried using: BoxPaint.setColor(AppShared.gResources.getColor(R.color.bwff_60)), the app still crashed. Please tell me what all changes I should make in the code so that I'll be able to see the view.
Logcat:
main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/com.md.areadectest"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/layoutMain" android:layout_width="wrap_content" android:layout_height="wrap_content">
<RelativeLayout android:layout_width="#dimen/width_320" android:layout_height="#dimen/width_240" android:layout_centerInParent="true">
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/preview">
</SurfaceView>
<FrameLayout android:layout_gravity="center" android:id="#+id/layoutDetectArea" android:background="#color/blue" android:layout_width="match_parent" android:layout_height="match_parent">
<com.md.areadectest.AreaDetectorView android:id="#+id/viewDetector" android:layout_width="match_parent" android:layout_height="match_parent" />
</FrameLayout>
</RelativeLayout>
</FrameLayout>
<LinearLayout
android:layout_below="#id/layoutMain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center">
</LinearLayout>
<ImageView android:id="#+id/myImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_android_black_24dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trigcount"
android:layout_alignTop="#+id/myImageView"
android:layout_centerHorizontal="true"
android:textColor="#android:color/white" />
</RelativeLayout>
View.java
public class AreaDetectorView extends LinearLayout {
public static int Width;
public static int Height;
private static Paint BoxPaint = null;
private static Paint BoxPaint2 = null;
private static Paint TextPaint = null;
private static Paint ArrowPaint = null;
private static Path mPath = null;
private static Rect mRect = null;
private static int lastX, lastY = 0;
private static boolean mBoxTouched = false;
private static boolean mArrowTouched = false;
private static Context mContext;
private static int ArrowWidth = 0;
public AreaDetectorView(Context context) {
super(context);
}
//attrs was not there
public AreaDetectorView(Context context, AttributeSet attrs) {
super(context,attrs);
// TODO Auto-generated constructor stub
if (!this.getRootView().isInEditMode()) {
ArrowWidth =GetDisplayPixel(context, 30);
}
//InitDetectionArea();
InitMemberVariables();
setWillNotDraw(false);
}
public static int GetDisplayPixel(Context paramContext, int paramInt)
{
return (int)(paramInt * paramContext.getResources().getDisplayMetrics().density + 0.5F);
}
public static void InitMemberVariables() {
if (BoxPaint == null) {
BoxPaint = new Paint();
BoxPaint.setAntiAlias(true);
BoxPaint.setStrokeWidth(2.0f);
//BoxPaint.setStyle(Style.STROKE);
BoxPaint.setStyle(Style.FILL_AND_STROKE);
BoxPaint.setColor(ContextCompat.getColor(mContext, R.color.bwff_60));
}
if (ArrowPaint == null) {
ArrowPaint = new Paint();
ArrowPaint.setAntiAlias(true);
ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.redDD));
ArrowPaint.setStyle(Style.FILL_AND_STROKE);
}
if (TextPaint == null) {
TextPaint = new Paint();
TextPaint.setColor(ContextCompat.getColor(mContext,R.color.yellowL));
TextPaint.setTextSize(16);
//txtPaint.setTypeface(lcd);
TextPaint.setStyle(Style.FILL_AND_STROKE);
}
if (mPath == null) {
mPath = new Path();
} else {
mPath.reset();
}
if (mRect == null) {
mRect = new Rect();
}
if (BoxPaint2 == null) {
BoxPaint2 = new Paint();
BoxPaint2.setAntiAlias(true);
BoxPaint2.setStrokeWidth(2.0f);
//BoxPaint.setStyle(Style.STROKE);
BoxPaint2.setStyle(Style.STROKE);
BoxPaint2.setColor(ContextCompat.getColor(mContext,R.color.bwff_9e));
}
}
public static void InitDetectionArea() {
try {
int w = Preferences.DetectionArea.width();
int h = Preferences.DetectionArea.height();
int x = Preferences.DetectionArea.left;
int y = Preferences.DetectionArea.top;
// ver 2.6.0
if (Preferences.DetectionArea.left == 1
&& Preferences.DetectionArea.top == 1
&& Preferences.DetectionArea.right == 1
&& Preferences.DetectionArea.bottom == 1) {
w = Preferences.DisplayWidth / 4;
h = Preferences.DisplayHeight / 3;
// ver 2.5.9
w = Width / 4;
h = Height / 3;
Preferences.DetectorWidth = w;
Preferences.DetectorHeight = h;
x = (Preferences.DisplayWidth / 2) - (w / 2);
y = (Preferences.DisplayHeight / 2) - (h / 2);
// ver 2.5.9
x = (Width / 2) - (w / 2);
y = (Height / 2) - (h / 2);
}
//Preferences.DetectionArea = new Rect(x, x, x + Preferences.DetectorWidth, x + Preferences.DetectorHeight);
Preferences.DetectionArea = new Rect(x, y, x + w, y + h);
Preferences.gDetectionBitmapInt = new int[Preferences.DetectionArea.width() * Preferences.DetectionArea.height()];
Preferences.gDetectionBitmapIntPrev = new int[Preferences.DetectionArea.width() * Preferences.DetectionArea.height()];
} catch (Exception e) {
e.printStackTrace();
}
}
public static void SetDetectionArea(int x, int y, int w, int h) {
try {
Preferences.DetectionArea = new Rect(x, y, w, h);
} catch (Exception e) {
e.printStackTrace();
}
}
private void DrawAreaBox(Canvas canvas) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
try {
if (this.getRootView().isInEditMode()) {
super.dispatchDraw(canvas);
return;
}
//Preferences.DetectionAreaOrient = UtilGeneralHelper.GetDetectRectByOrientation();
canvas.drawColor(0);
mPath.reset();
canvas.drawRect(Preferences.DetectionArea, BoxPaint);
mPath.moveTo(Preferences.DetectionArea.right - ArrowWidth, Preferences.DetectionArea.bottom);
mPath.lineTo(Preferences.DetectionArea.right, Preferences.DetectionArea.bottom - ArrowWidth);
mPath.lineTo(Preferences.DetectionArea.right, Preferences.DetectionArea.bottom);
mPath.lineTo(Preferences.DetectionArea.right - ArrowWidth, Preferences.DetectionArea.bottom);
mPath.close();
canvas.drawPath(mPath, ArrowPaint);
mPath.reset();
//canvas.drawRect(Preferences.DetectionAreaOrient, BoxPaint2);
//canvas.drawRect(Preferences.DetectionAreaOrientPort, BoxPaint2);
TextPaint.setTextSize(16);
TextPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff));
TextPaint.getTextBounds(getResources().getString(R.string.str_detectarea), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_detectarea),
Preferences.DetectionArea.left + 4,
Preferences.DetectionArea.top + 4 + mRect.height(),
TextPaint);
int recH = mRect.height();
TextPaint.setStrokeWidth(1.2f);
TextPaint.setTextSize(18);
TextPaint.setColor(ContextCompat.getColor(mContext,R.color.redD_9e));
TextPaint.getTextBounds(getResources().getString(R.string.str_dragandmove), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_dragandmove),
Preferences.DetectionArea.left + 4,
Preferences.DetectionArea.top + 20 + mRect.height()*2,
TextPaint);
TextPaint.getTextBounds(getResources().getString(R.string.str_scalearea), 0, 1, mRect);
canvas.drawText(getResources().getString(R.string.str_scalearea),
Preferences.DetectionArea.left + 4,
Preferences.DetectionArea.top + 36 + mRect.height()*3,
TextPaint);
super.dispatchDraw(canvas);
//canvas.restore();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onDraw(Canvas canvas) {
try {
super.onDraw(canvas);
invalidate();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
boolean retValue = true;
int X = (int)event.getX();
int Y = (int)event.getY();
//AppMain.txtLoc.setText(String.valueOf(X) + ", " + String.valueOf(Y));
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mBoxTouched = TouchedInBoxArea(X, Y);
//AppMain.txtLoc.setText("BoxTouched: " + String.valueOf(mBoxTouched));
if (!mBoxTouched) break;
lastX = X;
lastY = Y;
BoxPaint.setStyle(Style.FILL_AND_STROKE);
BoxPaint.setColor(ContextCompat.getColor(mContext,R.color.redD_9e));
mArrowTouched = TouchedInArrow(X, Y);
//AppMain.txtLoc.setText("ArrowTouched: " + String.valueOf(mBoxTouched));
if (mArrowTouched) {
ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff_9e));
}
break;
case MotionEvent.ACTION_MOVE:
if (!mBoxTouched) break;
int moveX = X - lastX;
int moveY = Y - lastY;
//AppMain.txtLoc.setText("Move X, Y: " + String.valueOf(moveX) + "," + String.valueOf(moveY));
if (!mArrowTouched) {
if (Preferences.DetectionArea.left + moveX < 0) {
break;
}
// if (Preferences.DetectionArea.right + moveX > Preferences.gDisplay.getWidth()) {
// break;
// }
// ver 2.5.9
if (Preferences.DetectionArea.right + moveX > Width) {
break;
}
if (Preferences.DetectionArea.top + moveY < 0) {
break;
}
// if (Preferences.DetectionArea.bottom + moveY > Preferences.gDisplay.getHeight()) {
// break;
// }
// ver 2.5.9
if (Preferences.DetectionArea.bottom + moveY > Height) {
break;
}
}
if (mArrowTouched) {
if ((Preferences.DetectionArea.width() + moveX) < ArrowWidth * 2){
break;
}
if ((Preferences.DetectionArea.height() + moveY) < ArrowWidth * 2) {
break;
}
Preferences.DetectionArea.right += moveX;
Preferences.DetectionArea.bottom += moveY;
//Log.i("DBG", "W,H: " + String.valueOf(Preferences.DetectionArea.width()) + "," + String.valueOf(Preferences.DetectionArea.height()));
} else {
Preferences.DetectionArea.left += moveX;
Preferences.DetectionArea.right += moveX;
Preferences.DetectionArea.top += moveY;
Preferences.DetectionArea.bottom += moveY;
}
lastX = X;
lastY = Y;
//AppMain.txtLoc.setText(String.valueOf(Preferences.DetectionArea.left) + ", " + String.valueOf(Preferences.DetectionArea.top));
break;
case MotionEvent.ACTION_UP:
mBoxTouched = false;
mArrowTouched = false;
//BoxPaint.setStyle(Style.STROKE);
BoxPaint.setStyle(Style.FILL_AND_STROKE);
BoxPaint.setColor(ContextCompat.getColor(mContext,R.color.bwff_60));
ArrowPaint.setColor(ContextCompat.getColor(mContext,R.color.redDD));
//AppMain.txtLoc.setText(String.valueOf(Preferences.DetectionArea.left) + ", " + String.valueOf(Preferences.DetectionArea.top));
if (Preferences.DetectionArea.left < 0) {
Preferences.DetectionArea.left = 0;
}
// if (Preferences.DetectionArea.right > Preferences.gDisplay.getWidth()) {
// Preferences.DetectionArea.right = Preferences.gDisplay.getWidth();
// }
// ver 2.5.9
if (Preferences.DetectionArea.right > Width) {
Preferences.DetectionArea.right = Width;
}
if (Preferences.DetectionArea.top < 0) {
Preferences.DetectionArea.top = 0;
}
// if (Preferences.DetectionArea.bottom > Preferences.gDisplay.getHeight()) {
// Preferences.DetectionArea.bottom = Preferences.gDisplay.getHeight();
// }
if (Preferences.DetectionArea.bottom > Height) {
Preferences.DetectionArea.bottom = Height;
}
Preferences.gDetectionBitmapInt = new int[Preferences.DetectionArea.width() * Preferences.DetectionArea.height()];
Preferences.gDetectionBitmapIntPrev = new int[Preferences.DetectionArea.width() * Preferences.DetectionArea.height()];
//Preferences.gDetectionBitmapInt = null;
//Preferences.gDetectionBitmapIntPrev = null;
String area = String.valueOf(Preferences.DetectionArea.left)
+ "," + String.valueOf(Preferences.DetectionArea.top)
+ "," + String.valueOf(Preferences.DetectionArea.right)
+ "," + String.valueOf(Preferences.DetectionArea.bottom);
// UtilGeneralHelper.SavePreferenceSetting(Preferences.gContext, Preferences.PREF_DETECTION_AREA_KEY, area);
break;
}
invalidate();
return retValue;
}
private boolean TouchedInBoxArea(int x, int y) {
boolean retValue = false;
try {
if (x > Preferences.DetectionArea.left && x < Preferences.DetectionArea.right) {
if (y > Preferences.DetectionArea.top && y < Preferences.DetectionArea.bottom) {
retValue = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retValue;
}
private boolean TouchedInArrow(int x, int y) {
boolean retValue = false;
try {
if (x > Preferences.DetectionArea.right - ArrowWidth && x < Preferences.DetectionArea.right) {
if (y > Preferences.DetectionArea.bottom - ArrowWidth && y < Preferences.DetectionArea.bottom) {
retValue = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return retValue;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
Width = width;
Height = height;
InitDetectionArea();
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
for (int i = 0; i < this.getChildCount()-1; i++){
(this.getChildAt(i)).layout(l, t, r, b);
}
if (changed) {
// check width height
if (r != Width || b != Height) {
// size does not match
}
}
}
}
The problem is that your variable mContextis null - you need to set mContext = context in your constructors.
Try this:
BoxPaint.setColor(getResources().getColor(R.color.bwff_60));
color only apply when you added in
your-project\app\src\main\res\values\colors.xml file.

How to fill the color gradually on drawn view canvas Android

I am having a WaveFormView on which I want to change the color of it while playing Audio file and as the Audio is paused it should be stopped coloring at that certain point and when resumed it should continue forward with coloring. I am not getting how to do it in my code..
This is the screen shot of my generated waveform. Now when I will click on Play button it should change the color of waveform gradually with red color (from start to end slowly).
Here is my code to draw waveform view.
WaveFormView.class
public class WaveformView extends View {
public interface WaveformListener {
public void waveformFling(float x);
public void waveformDraw();
}
;
// Colors
private Paint mGridPaint;
private Paint mSelectedLinePaint;
private Paint mUnselectedLinePaint;
private Paint mUnselectedBkgndLinePaint;
private Paint mBorderLinePaint;
private Paint mPlaybackLinePaint;
private Paint mTimecodePaint;
private SoundFile mSoundFile;
private int[] mLenByZoomLevel;
private double[][] mValuesByZoomLevel;
private double[] mZoomFactorByZoomLevel;
private int[] mHeightsAtThisZoomLevel;
private int mZoomLevel;
private int mNumZoomLevels;
private int mSampleRate;
private int mSamplesPerFrame;
private int mOffset;
private int mSelectionStart;
private int mSelectionEnd;
private int mPlaybackPos;
private float mDensity;
private float mInitialScaleSpan;
private WaveformListener mListener;
private GestureDetector mGestureDetector;
private ScaleGestureDetector mScaleGestureDetector;
private boolean mInitialized;
Color color;
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
// We don't want keys, the markers get these
setFocusable(false);
mGridPaint = new Paint();
mGridPaint.setAntiAlias(false);
mGridPaint.setColor(
getResources().getColor(R.color.grid_line));
mSelectedLinePaint = new Paint();
mSelectedLinePaint.setAntiAlias(false);
mSelectedLinePaint.setColor(
getResources().getColor(R.color.waveform_selected));
mUnselectedLinePaint = new Paint();
mUnselectedLinePaint.setAntiAlias(false);
mUnselectedLinePaint.setColor(
getResources().getColor(R.color.waveform_unselected));
mUnselectedBkgndLinePaint = new Paint();
mUnselectedBkgndLinePaint.setAntiAlias(false);
mUnselectedBkgndLinePaint.setColor(
getResources().getColor(
R.color.selection_border));
mBorderLinePaint = new Paint();
mBorderLinePaint.setAntiAlias(true);
mBorderLinePaint.setStrokeWidth(1.5f);
mBorderLinePaint.setPathEffect(
new DashPathEffect(new float[]{3.0f, 2.0f}, 0.0f));
mBorderLinePaint.setColor(
getResources().getColor(R.color.selection_border));
mPlaybackLinePaint = new Paint();
mPlaybackLinePaint.setAntiAlias(false);
mPlaybackLinePaint.setColor(
getResources().getColor(R.color.playback_indicator));
mTimecodePaint = new Paint();
mTimecodePaint.setTextSize(12);
mTimecodePaint.setAntiAlias(true);
mTimecodePaint.setColor(
getResources().getColor(R.color.timecode));
mTimecodePaint.setShadowLayer(
2, 1, 1,
getResources().getColor(R.color.timecode_shadow));
mGestureDetector = new GestureDetector(
context,
new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(
MotionEvent e1, MotionEvent e2, float vx, float vy) {
mListener.waveformFling(vx);
return true;
}
});
mSoundFile = null;
mLenByZoomLevel = null;
mValuesByZoomLevel = null;
mHeightsAtThisZoomLevel = null;
mOffset = 0;
mPlaybackPos = -1;
mSelectionStart = 0;
mSelectionEnd = 0;
mDensity = 1.0f;
mInitialized = false;
}
public boolean hasSoundFile() {
return mSoundFile != null;
}
public void setSoundFile(SoundFile soundFile) {
mSoundFile = soundFile;
mSampleRate = mSoundFile.getSampleRate();
mSamplesPerFrame = mSoundFile.getSamplesPerFrame();
computeDoublesForAllZoomLevels();
mHeightsAtThisZoomLevel = null;
}
/**
* Called once when a new sound file is added
*/
private void computeDoublesForAllZoomLevels() {
int numFrames = mSoundFile.getNumFrames();
int[] frameGains = mSoundFile.getFrameGains();
double[] smoothedGains = new double[numFrames];
if (numFrames == 1) {
smoothedGains[0] = frameGains[0];
} else if (numFrames == 2) {
smoothedGains[0] = frameGains[0];
smoothedGains[1] = frameGains[1];
} else if (numFrames > 2) {
smoothedGains[0] = (double)(
(frameGains[0] / 2.0) +
(frameGains[1] / 2.0));
for (int i = 1; i < numFrames - 1; i++) {
smoothedGains[i] = (double)(
(frameGains[i - 1] / 3.0) +
(frameGains[i ] / 3.0) +
(frameGains[i + 1] / 3.0));
}
smoothedGains[numFrames - 1] = (double)(
(frameGains[numFrames - 2] / 2.0) +
(frameGains[numFrames - 1] / 2.0));
}
// Make sure the range is no more than 0 - 255
double maxGain = 1.0;
for (int i = 0; i < numFrames; i++) {
if (smoothedGains[i] > maxGain) {
maxGain = smoothedGains[i];
}
}
double scaleFactor = 1.0;
if (maxGain > 255.0) {
scaleFactor = 255 / maxGain;
}
// Build histogram of 256 bins and figure out the new scaled max
maxGain = 0;
int gainHist[] = new int[256];
for (int i = 0; i < numFrames; i++) {
int smoothedGain = (int)(smoothedGains[i] * scaleFactor);
if (smoothedGain < 0)
smoothedGain = 0;
if (smoothedGain > 255)
smoothedGain = 255;
if (smoothedGain > maxGain)
maxGain = smoothedGain;
gainHist[smoothedGain]++;
}
// Re-calibrate the min to be 5%
double minGain = 0;
int sum = 0;
while (minGain < 255 && sum < numFrames / 20) {
sum += gainHist[(int)minGain];
minGain++;
}
// Re-calibrate the max to be 99%
sum = 0;
while (maxGain > 2 && sum < numFrames / 100) {
sum += gainHist[(int)maxGain];
maxGain--;
}
// Compute the heights
double[] heights = new double[numFrames];
double range = maxGain - minGain;
for (int i = 0; i < numFrames; i++) {
double value = (smoothedGains[i] * scaleFactor - minGain) / range;
if (value < 0.0)
value = 0.0;
if (value > 1.0)
value = 1.0;
heights[i] = value * value;
}
mNumZoomLevels = 5;
mLenByZoomLevel = new int[5];
mZoomFactorByZoomLevel = new double[5];
mValuesByZoomLevel = new double[5][];
// Level 0 is doubled, with interpolated values
mLenByZoomLevel[0] = numFrames * 2;
mZoomFactorByZoomLevel[0] = 2.0;
mValuesByZoomLevel[0] = new double[mLenByZoomLevel[0]];
if (numFrames > 0) {
mValuesByZoomLevel[0][0] = 0.5 * heights[0];
mValuesByZoomLevel[0][1] = heights[0];
}
for (int i = 1; i < numFrames; i++) {
mValuesByZoomLevel[0][2 * i] = 0.5 * (heights[i - 1] + heights[i]);
mValuesByZoomLevel[0][2 * i + 1] = heights[i];
}
// Level 1 is normal
mLenByZoomLevel[1] = numFrames;
mValuesByZoomLevel[1] = new double[mLenByZoomLevel[1]];
mZoomFactorByZoomLevel[1] = 1.0;
for (int i = 0; i < mLenByZoomLevel[1]; i++) {
mValuesByZoomLevel[1][i] = heights[i];
}
// 3 more levels are each halved
for (int j = 2; j < 5; j++) {
mLenByZoomLevel[j] = mLenByZoomLevel[j - 1] / 2;
mValuesByZoomLevel[j] = new double[mLenByZoomLevel[j]];
mZoomFactorByZoomLevel[j] = mZoomFactorByZoomLevel[j - 1] / 2.0;
for (int i = 0; i < mLenByZoomLevel[j]; i++) {
mValuesByZoomLevel[j][i] =
0.5 * (mValuesByZoomLevel[j - 1][2 * i] +
mValuesByZoomLevel[j - 1][2 * i + 1]);
}
}
if (numFrames > 5000) {
mZoomLevel = 3;
} else if (numFrames > 1000) {
mZoomLevel = 2;
} else if (numFrames > 300) {
mZoomLevel = 1;
} else {
mZoomLevel = 0;
}
mInitialized = true;
}
public boolean canZoomIn() {
return (mZoomLevel > 0);
}
public void zoomIn() {
if (canZoomIn()) {
mZoomLevel--;
mSelectionStart *= 2;
mSelectionEnd *= 2;
mHeightsAtThisZoomLevel = null;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter *= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
invalidate();
}
}
public boolean canZoomOut() {
return (mZoomLevel < mNumZoomLevels - 1);
}
public void zoomOut() {
if (canZoomOut()) {
mZoomLevel++;
mSelectionStart /= 2;
mSelectionEnd /= 2;
int offsetCenter = mOffset + getMeasuredWidth() / 2;
offsetCenter /= 2;
mOffset = offsetCenter - getMeasuredWidth() / 2;
if (mOffset < 0)
mOffset = 0;
mHeightsAtThisZoomLevel = null;
invalidate();
}
}
public double pixelsToSeconds(int pixels) {
double z = mZoomFactorByZoomLevel[mZoomLevel];
return (pixels * (double)mSamplesPerFrame / (mSampleRate * z));
}
public void setListener(WaveformListener listener) {
mListener = listener;
}
public void recomputeHeights(float density) {
mHeightsAtThisZoomLevel = null;
mDensity = density;
mTimecodePaint.setTextSize((int)(12 * density));
invalidate();
}
protected void drawWaveformLine(Canvas canvas,
int x, int y0, int y1,
Paint paint) {
canvas.drawLine(x, y0, x, y1, paint);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mSoundFile == null)
return;
if (mHeightsAtThisZoomLevel == null)
computeIntsForThisZoomLevel();
DisplayMetrics displaymetrics = getContext().getResources().getDisplayMetrics();
int height = displaymetrics.heightPixels;
int widths = displaymetrics.widthPixels;
// Draw waveform
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int start = mOffset;
int width = mHeightsAtThisZoomLevel.length - start;
int ctr = measuredHeight / 2;
Log.e("wid",String.valueOf(width));
Log.e("widCal",String.valueOf(mHeightsAtThisZoomLevel.length));
Log.e("widstart",String.valueOf(start));
if (width > measuredWidth)
width = measuredWidth;
Log.e("measured",String.valueOf(measuredWidth));
// Draw grid
double onePixelInSecs = pixelsToSeconds(1);
boolean onlyEveryFiveSecs = (onePixelInSecs > 1.0 / 50.0);
double fractionalSecs = mOffset * onePixelInSecs;
int integerSecs = (int) fractionalSecs;
int i = 0;
while (i < width) {
i++;
fractionalSecs += onePixelInSecs;
int integerSecsNew = (int) fractionalSecs;
if (integerSecsNew != integerSecs) {
integerSecs = integerSecsNew;
if (!onlyEveryFiveSecs || 0 == (integerSecs % 5)) {
canvas.drawLine(i, 0, i, measuredHeight, mGridPaint);
}
}
}
// Draw waveform
for ( i = 0; i < width; i++) {
Paint paint;
if (i + start >= mSelectionStart &&
i + start < mSelectionEnd) {
paint = mSelectedLinePaint;
// paint.setColor(color);
} else {
drawWaveformLine(canvas, ((widths/width)*i), 0, measuredHeight,
mUnselectedBkgndLinePaint);
paint = mUnselectedLinePaint;
}
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
paint);
if (i + start == mPlaybackPos) {
canvas.drawLine(i, 0, i, measuredHeight, mPlaybackLinePaint);
}
}
if (mListener != null) {
mListener.waveformDraw();
}
}
private void computeIntsForThisZoomLevel() {
int halfHeight = (getMeasuredHeight() / 2) - 1;
mHeightsAtThisZoomLevel = new int[mLenByZoomLevel[mZoomLevel]];
for (int i = 0; i < mLenByZoomLevel[mZoomLevel]; i++) {
mHeightsAtThisZoomLevel[i] =
(int)(mValuesByZoomLevel[mZoomLevel][i] * halfHeight);
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity implements WaveformView.WaveformListener {
WaveformView mWaveformView;
SoundFile mSoundFile;
private float mDensity;
private File mFile;
private String mFilename;
private long mLoadingLastUpdateTime;
boolean mLoadingKeepGoing;
boolean mFinishActivity;
private ProgressDialog mProgressDialog;
String mTitle,mArtist;
private Thread mLoadSoundFileThread;
private Thread mRecordAudioThread;
private Thread mSaveSoundFileThread;
private boolean mIsPlaying;
private SamplePlayer mPlayer;
private String mInfoContent;
private int mWidth;
private int mMaxPos;
private int mStartPos;
private int mEndPos;
private boolean mStartVisible;
private boolean mEndVisible;
private int mLastDisplayedStartPos;
private int mLastDisplayedEndPos;
private int mOffset;
private int mOffsetGoal;
private int mFlingVelocity;
private int mPlayStartMsec;
private int mPlayEndMsec;
private Handler mHandler;
Button pla;
MediaPlayer mediaPlayer;
boolean ismIsPlaying;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pla = (Button)findViewById(R.id.play);
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
mHandler = new Handler();
Uri uri = Uri.parse("/sdcard/audio_file.mp3");
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
loadGui();
loadFromFile();
}
/**
* Called from both onCreate and onConfigurationChanged
* (if the user switched layouts)
*/
private void loadGui() {
// Inflate our UI from its XML layout description.
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mDensity = metrics.density;
mWaveformView = (WaveformView)findViewById(R.id.waveform);
mWaveformView.setListener(this);
if (mSoundFile != null && !mWaveformView.hasSoundFile()) {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
}
}
private void loadFromFile() {
mFilename = "/sdcard/audio_file.mp3";
mFile = new File(mFilename);
SongMetadataReader metadataReader = new SongMetadataReader(
this, mFilename);
mTitle = metadataReader.mTitle;
mArtist = metadataReader.mArtist;
String titleLabel = mTitle;
if (mArtist != null && mArtist.length() > 0) {
titleLabel += " - " + mArtist;
}
setTitle(titleLabel);
mLoadingLastUpdateTime = getCurrentTime();
mLoadingKeepGoing = true;
mFinishActivity = false;
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setTitle("Loading...");
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
mLoadingKeepGoing = false;
mFinishActivity = true;
}
});
mProgressDialog.show();
final SoundFile.ProgressListener listener =
new SoundFile.ProgressListener() {
public boolean reportProgress(double fractionComplete) {
long now = getCurrentTime();
if (now - mLoadingLastUpdateTime > 100) {
mProgressDialog.setProgress(
(int) (mProgressDialog.getMax() * fractionComplete));
mLoadingLastUpdateTime = now;
}
return mLoadingKeepGoing;
}
};
// Load the sound file in a background thread
mLoadSoundFileThread = new Thread() {
public void run() {
try {
mSoundFile = SoundFile.create(mFile.getAbsolutePath(), listener);
if (mSoundFile == null) {
mProgressDialog.dismiss();
String name = mFile.getName().toLowerCase();
String[] components = name.split("\\.");
String err;
if (components.length < 2) {
err = getResources().getString(
R.string.no_extension_error);
} else {
err = getResources().getString(
R.string.bad_extension_error) + " " +
components[components.length - 1];
}
final String finalErr = err;
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(new Exception(), finalErr);
}
};
mHandler.post(runnable);
return;
}
mPlayer = new SamplePlayer(mSoundFile);
} catch (final Exception e) {
mProgressDialog.dismiss();
e.printStackTrace();
mInfoContent = e.toString();
runOnUiThread(new Runnable() {
public void run() {
}
});
Runnable runnable = new Runnable() {
public void run() {
showFinalAlert(e, getResources().getText(R.string.read_error));
}
};
mHandler.post(runnable);
return;
}
mProgressDialog.dismiss();
if (mLoadingKeepGoing) {
Runnable runnable = new Runnable() {
public void run() {
finishOpeningSoundFile();
}
};
mHandler.post(runnable);
} else if (mFinishActivity){
MainActivity.this.finish();
}
}
};
mLoadSoundFileThread.start();
}
private void finishOpeningSoundFile() {
mWaveformView.setSoundFile(mSoundFile);
mWaveformView.recomputeHeights(mDensity);
Log.e("sound file",mFilename);
Log.e("sound", String.valueOf(mSoundFile));
}
/**
* Show a "final" alert dialog that will exit the activity
* after the user clicks on the OK button. If an exception
* is passed, it's assumed to be an error condition, and the
* dialog is presented as an error, and the stack trace is
* logged. If there's no exception, it's a success message.
*/
private void showFinalAlert(Exception e, CharSequence message) {
CharSequence title;
if (e != null) {
Log.e("Ringdroid", "Error: " + message);
Log.e("Ringdroid", getStackTrace(e));
title = getResources().getText(R.string.alert_title_failure);
setResult(RESULT_CANCELED, new Intent());
} else {
Log.v("Ringdroid", "Success: " + message);
title = getResources().getText(R.string.alert_title_success);
}
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void showFinalAlert(Exception e, int messageResourceId) {
showFinalAlert(e, getResources().getText(messageResourceId));
}
#Override
public void waveformTouchStart(float x) {
}
#Override
public void waveformTouchMove(float x) {
}
#Override
public void waveformTouchEnd() {
}
#Override
public void waveformFling(float x) {
}
#Override
public void waveformDraw() {
mWidth = mWaveformView.getMeasuredWidth();
if (mOffsetGoal != mOffset) {
// updateDisplay();
}
else if (mIsPlaying) {
// updateDisplay();
} else if (mFlingVelocity != 0) {
// updateDisplay();
}
}
private long getCurrentTime() {
return System.nanoTime() / 1000000;
}
private String getStackTrace(Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
return writer.toString();
}
public void buttonClick(View view) {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
ismIsPlaying = true;
}
}
In your onDraw(Canvas canvas) add the following lines
if (i + start <= mPlaybackPos) {
Paint mPaint = new Paint(paint);
mPaint.setColor(Color.RED);
drawWaveformLine(
canvas, ((widths/width)*i),
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
mPaint);
}
add them above the line:
if (i + start == mPlaybackPos) {
And if this works, consider to allocate the Paint-object outside the onDraw() method.

Radar animation android

So here is the thing. I am monitoring certain distances, and i would like to display them in a radar animation. The base radar image would be something like this (not exactly)
where every circle means a distance range. The idea is that the dot moves towards the circles as the distance changes. My initial approach was to make different images of the same radar with the dot on each circle and simply switch them according the distance. But then i wonder if there any chance(performant, and that works fine on different resolutions) to have one base image of the radar and simply move the dot. I hope I am being clear and if anyone has an idea i would be very thankful
I am not posting any code, cause i need the idea, then ill struggle with the implementation
Have you tried these examples?
https://github.com/jfabrix101/RadarCustomVIew
https://github.com/gpfduoduo/RadarScanView
i.e
Radar.java
public class RadarView extends View {
private final String LOG = "RadarView";
private final int POINT_ARRAY_SIZE = 25;
private int fps = 100;
private boolean showCircles = true;
float alpha = 0;
Point latestPoint[] = new Point[POINT_ARRAY_SIZE];
Paint latestPaint[] = new Paint[POINT_ARRAY_SIZE];
public RadarView(Context context) {
this(context, null);
}
public RadarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RadarView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Paint localPaint = new Paint();
localPaint.setColor(Color.GREEN);
localPaint.setAntiAlias(true);
localPaint.setStyle(Paint.Style.STROKE);
localPaint.setStrokeWidth(1.0F);
localPaint.setAlpha(0);
int alpha_step = 255 / POINT_ARRAY_SIZE;
for (int i=0; i < latestPaint.length; i++) {
latestPaint[i] = new Paint(localPaint);
latestPaint[i].setAlpha(255 - (i* alpha_step));
}
}
android.os.Handler mHandler = new android.os.Handler();
Runnable mTick = new Runnable() {
#Override
public void run() {
invalidate();
mHandler.postDelayed(this, 1000 / fps);
}
};
public void startAnimation() {
mHandler.removeCallbacks(mTick);
mHandler.post(mTick);
}
public void stopAnimation() {
mHandler.removeCallbacks(mTick);
}
public void setFrameRate(int fps) { this.fps = fps; }
public int getFrameRate() { return this.fps; };
public void setShowCircles(boolean showCircles) { this.showCircles = showCircles; }
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int r = Math.min(width, height);
//canvas.drawRect(0, 0, getWidth(), getHeight(), localPaint);
int i = r / 2;
int j = i - 1;
Paint localPaint = latestPaint[0]; // GREEN
if (showCircles) {
canvas.drawCircle(i, i, j, localPaint);
canvas.drawCircle(i, i, j, localPaint);
canvas.drawCircle(i, i, j * 3 / 4, localPaint);
canvas.drawCircle(i, i, j >> 1, localPaint);
canvas.drawCircle(i, i, j >> 2, localPaint);
}
alpha -= 0.5;
if (alpha < -360) alpha = 0;
double angle = Math.toRadians(alpha);
int offsetX = (int) (i + (float)(i * Math.cos(angle)));
int offsetY = (int) (i - (float)(i * Math.sin(angle)));
latestPoint[0]= new Point(offsetX, offsetY);
for (int x=POINT_ARRAY_SIZE-1; x > 0; x--) {
latestPoint[x] = latestPoint[x-1];
}
int lines = 0;
for (int x = 0; x < POINT_ARRAY_SIZE; x++) {
Point point = latestPoint[x];
if (point != null) {
canvas.drawLine(i, i, point.x, point.y, latestPaint[x]);
}
}
lines = 0;
for (Point p : latestPoint) if (p != null) lines++;
boolean debug = false;
if (debug) {
StringBuilder sb = new StringBuilder(" >> ");
for (Point p : latestPoint) {
if (p != null) sb.append(" (" + p.x + "x" + p.y + ")");
}
Log.d(LOG, sb.toString());
// " - R:" + r + ", i=" + i +
// " - Size: " + width + "x" + height +
// " - Angle: " + angle +
// " - Offset: " + offsetX + "," + offsetY);
}
}
}
in your activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/black">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start"
android:onClick="startAniamtion"/>
<frusso.radartest.RadarView
android:id="#+id/radarView"
android:layout_width="240dp"
android:layout_height="240dp"
android:layout_gravity="center_horizontal"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop"
android:onClick="stopAnimation"/>
Activity.java
public class MainActivity extends Activity {
RadarView mRadarView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRadarView = (RadarView) findViewById(R.id.radarView);
mRadarView.setShowCircles(true);
}
public void stopAnimation(View view) {
if (mRadarView != null) mRadarView.stopAnimation();
}
public void startAnimation(View view) {
if (mRadarView != null) mRadarView.startAnimation();
}
}
Hope this will guide you for your requirement.
My approach would be to have one static image of the radar and another of the dot (if you wanted a custom one). I'd have 2 main threads, the game loop and one that moves the dot on your radar image based on your position.
"I am monitoring certain distances" ~ What does that mean?
To make a radar create a class that extends ImageView. Override onDraw(Canvas canvas) and set the image resource to a radar background.
#Override
public void onDraw(Canvas canvas) {
//draw background
super.onDraw(canvas);
for(PointF p : points)
{
//draw each point as an image. Maybe, translate by width/2 and height/2
}
}

Create waveform of audio file in android [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to create the wave forms of audio file in android. Can anyone provide me an example source code?
Create class and extend View. Then create Listener interface for your class.
public class WaveformCls extends View {
public interface WaveformListener {
public void waveformTouchStart(float x);
public void waveformTouchMove(float x);
public void waveformTouchEnd();
public void waveformFling(float x);
public void waveformDraw();
};
Create Paint object as per your requirement.
Create one method which is initialized all Paint object.
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
// We don't want keys, the markers get these
setFocusable(false);
mGridPaint = new Paint();
mGridPaint.setAntiAlias(false);
mGridPaint.setColor(
getResources().getColor(R.drawable.grid_line));
mSelectedLinePaint = new Paint();
mSelectedLinePaint.setAntiAlias(false);
mSelectedLinePaint.setColor(
getResources().getColor(R.drawable.waveform_selected));
mUnselectedLinePaint = new Paint();
mUnselectedLinePaint.setAntiAlias(false);
mUnselectedLinePaint.setColor(
getResources().getColor(R.drawable.waveform_unselected));
mUnselectedBkgndLinePaint = new Paint();
mUnselectedBkgndLinePaint.setAntiAlias(false);
mUnselectedBkgndLinePaint.setColor(
getResources().getColor(
R.drawable.waveform_unselected_bkgnd_overlay));
mBorderLinePaint = new Paint();
mBorderLinePaint.setAntiAlias(true);
mBorderLinePaint.setStrokeWidth(1.5f);
mBorderLinePaint.setPathEffect(
new DashPathEffect(new float[] { 3.0f, 2.0f }, 0.0f));
mBorderLinePaint.setColor(
getResources().getColor(R.drawable.selection_border));
mPlaybackLinePaint = new Paint();
mPlaybackLinePaint.setAntiAlias(false);
mPlaybackLinePaint.setColor(
getResources().getColor(R.drawable.playback_indicator));
mTimecodePaint = new Paint();
mTimecodePaint.setTextSize(12);
mTimecodePaint.setAntiAlias(true);
mTimecodePaint.setColor(
getResources().getColor(R.drawable.timecode));
mTimecodePaint.setShadowLayer(
2, 1, 1,
getResources().getColor(R.drawable.timecode_shadow));
mGestureDetector = new GestureDetector(
context,
new GestureDetector.SimpleOnGestureListener() {
public boolean onFling(
MotionEvent e1, MotionEvent e2, float vx, float vy) {
mListener.waveformFling(vx);
return true;
}
});
mSoundFile = null;
mLenByZoomLevel = null;
mValuesByZoomLevel = null;
mHeightsAtThisZoomLevel = null;
mOffset = 0;
mPlaybackPos = -1;
mSelectionStart = 0;
mSelectionEnd = 0;
mDensity = 1.0f;
mInitialized = false;
}
You need to override onTouchEvent
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
mListener.waveformTouchStart(event.getX());
break;
case MotionEvent.ACTION_MOVE:
mListener.waveformTouchMove(event.getX());
break;
case MotionEvent.ACTION_UP:
mListener.waveformTouchEnd();
break;
}
return true;
}
public void setSoundFile(CheapSoundFile soundFile) {
mSoundFile = soundFile;
mSampleRate = mSoundFile.getSampleRate();
mSamplesPerFrame = mSoundFile.getSamplesPerFrame();
computeDoublesForAllZoomLevels();
mHeightsAtThisZoomLevel = null;
}
override the draw method which draw wave on your screen.
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mSoundFile == null)
return;
if (mHeightsAtThisZoomLevel == null)
computeIntsForThisZoomLevel();
// Draw waveform
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
int start = mOffset;
int width = mHeightsAtThisZoomLevel.length - start;
int ctr = measuredHeight / 2;
if (width > measuredWidth)
width = measuredWidth;
// Draw grid
double onePixelInSecs = pixelsToSeconds(1);
boolean onlyEveryFiveSecs = (onePixelInSecs > 1.0 / 50.0);
double fractionalSecs = mOffset * onePixelInSecs;
int integerSecs = (int) fractionalSecs;
int i = 0;
while (i < width) {
i++;
fractionalSecs += onePixelInSecs;
int integerSecsNew = (int) fractionalSecs;
if (integerSecsNew != integerSecs) {
integerSecs = integerSecsNew;
if (!onlyEveryFiveSecs || 0 == (integerSecs % 5)) {
canvas.drawLine(i, 0, i, measuredHeight, mGridPaint);
}
}
}
// Draw waveform
for (i = 0; i < width; i++) {
Paint paint;
if (i + start >= mSelectionStart &&
i + start < mSelectionEnd) {
paint = mSelectedLinePaint;
} else {
drawWaveformLine(canvas, i, 0, measuredHeight,
mUnselectedBkgndLinePaint);
paint = mUnselectedLinePaint;
}
drawWaveformLine(
canvas, i,
ctr - mHeightsAtThisZoomLevel[start + i],
ctr + 1 + mHeightsAtThisZoomLevel[start + i],
paint);
if (i + start == mPlaybackPos) {
canvas.drawLine(i, 0, i, measuredHeight, mPlaybackLinePaint);
}
}
// If we can see the right edge of the waveform, draw the
// non-waveform area to the right as unselected
for (i = width; i < measuredWidth; i++) {
drawWaveformLine(canvas, i, 0, measuredHeight,
mUnselectedBkgndLinePaint);
}
// Draw borders
canvas.drawLine(
mSelectionStart - mOffset + 0.5f, 30,
mSelectionStart - mOffset + 0.5f, measuredHeight,
mBorderLinePaint);
canvas.drawLine(
mSelectionEnd - mOffset + 0.5f, 0,
mSelectionEnd - mOffset + 0.5f, measuredHeight - 30,
mBorderLinePaint);
// Draw timecode
double timecodeIntervalSecs = 1.0;
if (timecodeIntervalSecs / onePixelInSecs < 50) {
timecodeIntervalSecs = 5.0;
}
if (timecodeIntervalSecs / onePixelInSecs < 50) {
timecodeIntervalSecs = 15.0;
}
// Draw grid
fractionalSecs = mOffset * onePixelInSecs;
int integerTimecode = (int) (fractionalSecs / timecodeIntervalSecs);
i = 0;
while (i < width) {
i++;
fractionalSecs += onePixelInSecs;
integerSecs = (int) fractionalSecs;
int integerTimecodeNew = (int) (fractionalSecs /
timecodeIntervalSecs);
if (integerTimecodeNew != integerTimecode) {
integerTimecode = integerTimecodeNew;
// Turn, e.g. 67 seconds into "1:07"
String timecodeMinutes = "" + (integerSecs / 60);
String timecodeSeconds = "" + (integerSecs % 60);
if ((integerSecs % 60) < 10) {
timecodeSeconds = "0" + timecodeSeconds;
}
String timecodeStr = timecodeMinutes + ":" + timecodeSeconds;
float offset = (float) (
0.5 * mTimecodePaint.measureText(timecodeStr));
canvas.drawText(timecodeStr,
i - offset,
(int)(12 * mDensity),
mTimecodePaint);
}
}
if (mListener != null) {
mListener.waveformDraw();
}
}
Here is complete source code of Rindroid which is useful for you
Source code for waveform

how to display label (textview) in pie chart items?

I want to display the labels on pie chart items..please guide me..
Main.java:-
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PieDetailsItem item;
int maxCount=0;
int itemCount=0;
int items[]={2,6,0};
int colors[]={-6777216,-16776961,-16711681};
String itemslabel[]={" vauesr ur 100"," vauesr ur 200"," vauesr ur 300"};
for(int i=0;i<items.length;i++)
{
itemCount=items[i];
item=new PieDetailsItem();
item.count=itemCount;
item.label=itemslabel[i];
item.color=colors[i];
piedata.add(item);
maxCount=maxCount+itemCount;
}
int size=155;
int BgColor=0xffa11b1;
Bitmap mBaggroundImage=Bitmap.createBitmap(size,size,Bitmap.Config.ARGB_8888);
View_PieChart piechart=new View_PieChart(this);
piechart.setLayoutParams(new LayoutParams(size,size));
piechart.setGeometry(size, size, 2, 2, 2, 2, 2130837504);
piechart.setSkinparams(BgColor);
piechart.setData(piedata, maxCount);
piechart.invalidate();
piechart.draw(new Canvas(mBaggroundImage));
piechart=null;
ImageView mImageView=new ImageView(this);
mImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
mImageView.setBackgroundColor(BgColor);
mImageView.setImageBitmap(mBaggroundImage);
LinearLayout finalLayout=(LinearLayout)findViewById(R.id.pie_container);
finalLayout.addView(mImageView);
}
View_piechart.java:-
public View_PieChart(Context context) {
super(context);
Log.w(" single cons ", " single cons");
}
public View_PieChart(Context context, AttributeSet attr) {
super(context, attr);
Log.w(" double cons ", " double cons");
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mState != IS_READY_TO_DRAW) {
return;
}
canvas.drawColor(mBgcolor);
mBagpaints.setAntiAlias(true);
mBagpaints.setStyle(Paint.Style.FILL);
mBagpaints.setColor(0x88FF0000);
mBagpaints.setStrokeWidth(0.0f);
mLinePaints.setAntiAlias(true);
mLinePaints.setColor(0xff000000);
mLinePaints.setStrokeWidth(3.0f);
mLinePaints.setStyle(Paint.Style.STROKE);
RectF mOvals = new RectF(mGapleft, mGapTop, mWidth - mGapright, mHeight
- mGapBottm);
mStart = START_INC;
PieDetailsItem item;
for (int i = 0; i < mdataArray.size(); i++) {
item = (PieDetailsItem) mdataArray.get(i);
mBagpaints.setColor(item.color);
mSweep = (float) 360* ((float) item.count / (float) mMaxConnection);
canvas.drawArc(mOvals, mStart, mSweep, true, mBagpaints);
canvas.drawArc(mOvals, mStart, mSweep, true, mLinePaints);
mStart = mStart + mSweep;
}
mState = IS_DRAW;
}
public void setGeometry(int width, int height, int gapleft, int gapright,
int gaptop, int gapbottom, int overlayid) {
mWidth = width;
mHeight = height;
mGapleft = gapleft;
mGapright = gapright;
mGapBottm = gapbottom;
mGapTop = gaptop;
}
public void setSkinparams(int bgcolor) {
Log.w(" Set bg color : ", bgcolor + "");
mBgcolor = bgcolor;
}
public void setData(List<PieDetailsItem> data, int maxconnection) {
mdataArray = data;
mMaxConnection = maxconnection;
Log.w(" Max Connection ", maxconnection + " " + " Adataarray :"
+ data.toString());
mState = IS_READY_TO_DRAW;
}
public void setState(int state) {
mState = state;
}
public int getColorValues(int index) {
if (mdataArray == null) {
return 0;
}
else if (index < 0)
return ((PieDetailsItem) mdataArray.get(0)).color;
else if (index > mdataArray.size())
return ((PieDetailsItem) mdataArray.get(mdataArray.size() - 1)).color;
else
return ((PieDetailsItem) mdataArray.get(mdataArray.size() - 1)).color;
}
main.xml
>
<LinearLayout android:id="#+id/pie_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
You're not going to use a TextView, you're just going to draw the text right on top of your pies.
refer to this:
Android Canvas.drawText
Post xml layouts for the views that you want.

Categories

Resources