AudioTrack- Generate Sine Wave - Android Software Development

Hi All,
I am attempting to generate a signal at a dynamically chosen frequency (i.e. 50-20000 Hz approx.) I am starting to get frustrated. I've read the documentation over and over again, looked at numerous examples and forum posts but have not resolved the problem.
The code works BUT the signal is not stable going up and down slightly.
Code:
final float frequency = freq;
float increment = (float)((2*Math.PI) * frequency / 44100); // angular increment for each sample
float angle = 0;
AndroidAudioDevice device = new AndroidAudioDevice( );
float samples[] = new float[1024];
while(threadIsRunning)
{
for( int i = 0; i < samples.length; i++ )
{
samples[i] = (float)Math.sin( angle );
angle += increment;
}
device.writeSamples( samples );
}
and the the AndroidAudioDevice Class is as follows:
Code:
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
public class AndroidAudioDevice {
AudioTrack track;
short[] buffer = new short[1024];
public AndroidAudioDevice( )
{
int minSize =AudioTrack.getMinBufferSize( 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT );
track = new AudioTrack( AudioManager.STREAM_MUSIC, 44100,
AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,
minSize, AudioTrack.MODE_STREAM);
track.play();
}
public void writeSamples(float[] samples)
{
fillBuffer( samples );
track.write( buffer, 0, samples.length );
}
private void fillBuffer( float[] samples )
{
if( buffer.length < samples.length )
buffer = new short[samples.length];
for( int i = 0; i < samples.length; i++ )
buffer[i] = (short)(samples[i] * Short.MAX_VALUE);
}
public void releaseTrack(){
track.release();
}
}
Where is the problem here? Is there an alternative way of solving this problem?
I would very much appreciate if you were able to help, even if its only a pointer in the right direction! Have lost a lot of hours over this puppy.
-Thanks in advance

do you really need a wavelike form? why not just plot each point as Y-axis and keep the x as time...just do it really fast and you get a wave-sorta.....
-hope i helped

? I'm not exactly sure what you mean. I am essentially plotting a wave function, just filling a buffer "x-axis" with "y-axis" the sine values.

You actually are not creating a perfect sin wave because the samples array does not have a complete period.
According your code you need frequency * 44100 samples to have the entire period.
Your actual implementation create a wave that does not match the end of samples array with the beginning of the next samples array sent to the device, it creates a little peak and it is what you notice.

Could you please expand on that Alerias.The way I see it the samples don't contain a full sine wave but they do keep going where they left of from one sample to the next. And I don't think there should be a peak changing from one sample to the next.
Code:
angle += increment;
The angle Variable is continuously and uniformly incremented. So if the sample a's last entry is
Code:
samples[i] = (float)Math.sin( angle );
The first entry of the next sample will be
Code:
samples[i] = (float)Math.sin( angle +increment);
I therefore don't see a discontinuity. The angle variable does not get re-initiated to 0.
Thanks a lot,
FlyingSwissman

Related

Paint with the finger

Hello to all!
I have not participated much in the forum, though I have been reading you for a while So... I am going to ask for your help
I'm trying to make a custom paint with the finger (to draw, to take notes, whatever) and I'm having some troubles.
Up to now, from what I have read, I'm using a class extended from View implementing OnTouchListener , and using the onDraw() method, with the onTouch event. I detect when the screen is touched (pressed, or dragged to "paint" in the screen) with the onTouch method, store the last point in an array, and in the onDraw method, I paint all the array.
-As my knowledge goes, in the onDraw method, you have to re-paint all the canvas (this is translated to my problem, to repaint all the stroke or "painting"). Is this correct or I am doing anything wrong? Is there any way to only update the current canvas, and not have to re-paint all the screen? Maybe using othe classes or other methods, but I have found nothing in the net (maybe I'm not looking in the correct places).
- The second problem I found is that when I drag the finger across the screen, sometimes the ontouch method doesen't capture all the points I have "touched" with the finger. I mean, I don't want to capture ALL the points, but when I drag the finger with moderate speed (not very fast) there are important gaps in between. Is there a way to optimize this and try to capture more points in between?
So far, this is the code I have relevant to the issues I'm explaining:
I'm trying to copy the code but I get a error (It sais I can not post outside links, but I'm not posting any links, just the code)
Code:
private ArrayList<PointStroke > stroke= new ArrayList<PointStroke >();
protected void onDraw(Canvas canvas) {
Paint p = new Paint();
p.setColor(Color.RED);
int signLength = stroke.size();
PointStroke pf;
PointStroke pfant;
for (int index = 0; index < signLength; index++) {
pf = stroke.get(index);
canvas.drawCircle(pf.x,pf.y,7,p);
if (index > 0 ) {
pfant = stroke.get(index-1);
canvas.drawLine(pfant.x, pfant.y, pf.x, pf.y, p);
}
}
canvas.drawCircle(x,y,7,p);
invalidate();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
x = event.getX();
y = event.getY();
pr = event.getPressure();
sz = event.getSize();
long now = System.currentTimeMillis();
stroke.add(new PointStroke(x,y,pr,sz,now));
return true;
}
private class PointStroke{
public float x;
public float y;
public float pr;
public float sz;
public long time;
public PointStroke(float newX, float newY, float newPR, float newSZ, long newTIME) {
x = newX;
y = newY;
pr = newPR;
sz = newSZ;
time = newTIME;
}
}
Thanks for all your answers and the time to read and answer!

[Q] Making selected spinner items into array references

Hello, i'm making an app, and i need for the app to populate a list view, i've got this to work, the listview is populated by arrays in the values resources folder. the name for this array is defined by the selected items of two spinners combined with a "_" in the middle. How do i set this custom array ID?
here is my current main activity code: (i've used a existing array id to test that it works "tener_future")
Code:
package org.townsend.spanish.donate;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
public class Main extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View conjugateButton = findViewById(R.id.conjugate_button);
conjugateButton.setOnClickListener(this);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void verbAndTense() {
Resources res = getResources();
String[] listItems = res.getStringArray(R.array.tener_conditional);
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.conjugate_button:
verbAndTense();
break;
}
}
}
If I understand your question correctly, you are trying to get a reference to an Id stored in the R class, but which reference you need changes at runtime?
If that is the case, I think you may want to program a custom utility/method that can return the correct R reference for you. R is just a static generated class of ints, so it cannot evaluate something like R.id.dynamicterm1_dynamicterm2 where dynamicterm1 and dynamicterm2 change at runtime.
One way to do this might be a static util class like this:
Code:
package org.townsend.spanish.donate.util;
import org.townsend.spanish.donate.R;
public class ReferenceFinder
{
public static int find(String prefixName, String suffixName)
{
int returnValue = -1; // -1 indicates an error
if ( prefixName.equals("verb") && suffixName.equals("tense") )
{
returnValue = R.id.verb_tense;
}
else if( prefixName.equals("adj") && suffixName.equals("tense") )
{
returnValue = R.id.adjective_tense;
}
return returnValue;
}
Then you would call it like so:
Code:
Resources res = getResources();
int resourceID = ReferenceFinder.find("verb", "tense") ;
String[] listItems = res.getStringArray( resourceID );
I'm sure there are other ways to do this, but this is the first that came to mind. Hope that helps
would that mean that in the resource finder class that i'd have to define every possible outcome? because i'll have hundreds of outcomes once i have loaded the full list's and their outcome array's
and i think you have understood me correctly, basically it's and app (for spanish) where in one spinner you input a verb, in another you input a tense, and when you press a button it fills a list view with the 6 conjugations.
also it seems like in the second snippet of code i would have to actually set the "verb" and "tense" or could i put something dynamic like
Code:
verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem
Thanks for the help
hmm.... you might be able to do it via reflection actually, so that you wouldnt have to define each one.
I'm not 100% sure what the code would be but it would probably looks something like this:
Code:
String className= "com.example.myapp.R.id";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
int resourceID = f.getInt ( new Object() );
ok thanks i'm trying to get it to fit in, and i believe i have:
Code:
@SuppressWarnings({ "unchecked", "rawtypes" })
private void verbAndTense() {
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
verb_tenses.getSelectedItem();
String className= "org.townsend.spanish.donate.R.array";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
int resourceID = f.getInt ( new Object() );
String[] listItems = f.getStringArray( resourceID );
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));
}
where it says :
Code:
String[] listItems = f.getStringArray( resourceID );
is it correct to put the "f" in there? and second is asks to define "Field" what should i import it as? or do i need to declare it in another format?
should be something like
String[] listItems = getResources.getStringArray( resourceID );
resourceID is an int just like R.id.something_something
i changed getResources to res, since it was defined as:
Code:
Resources res = getResources();
however my problem with "Field" in the line:
Code:
Field f = cl.getDeclaredField ( fieldName );
still exists, it says "Field cannot be resolved to a type" and gives me a load of options including imports, making a new class, interface, enum or adding a parameter. what should i do? I've tried several of the imports but then other segments suchs as:
Code:
cl.getDeclaredField ( fieldName );
become errored.
Thank you for all your guys' help so far
If you're using the Field class and don't IMPORT it, well, that's a problem
You're best friend --> http://developer.android.com/reference/java/lang/reflect/Field.html
thank you yes my porblem was i was unsure which to import it as, although i was more confident about it being that one (i had about 8 options from eclipse)
previous code however has now given me errors, :
Code:
Class cl = [U]Class.forName( className )[/U];
this section saying : "Unhandled exception type ClassNotFoundException"
Code:
Field f = [U]cl.getDeclaredField ( fieldName )[/U];
this with: "Unhandled exception type NoSuchFieldException"
and
Code:
int resourceID = [U]f.getInt ( new Object() )[/U];
with: "Unhandled exception type IllegalAccessException"
I looked through the field resource page and the last one where it says this error occurs when the field is not accesible....:/
I then checked the Class resources page and the first one said that type ClassNotFoundException is thrown when requested class cannot be found, and i thought i had declarred it in the previous
Code:
String className= "org.townsend.spanish.donate.R.array";
I know that in the example you provided me you put R.id, howeve this is a value array so it should be array right?
and the second says its thrown when the field cannot be found.
Im guessing that means that the first one is affecting the rest? how could i correct this,
if you wish to see the entire void it is here
Code:
@SuppressWarnings({ "rawtypes", "unchecked" })
private void verbAndTense() {
Spinner verbs = (Spinner) findViewById(R.id.verbs);
Spinner verb_tenses = (Spinner) findViewById(R.id.verb_tenses);
verb_tenses.getSelectedItem();
String className= "org.townsend.spanish.donate.R.array";
Class cl = Class.forName( className );
String fieldName = verbs.getSelectedItem() + "_" + verb_tenses.getSelectedItem();
Field f = cl.getDeclaredField ( fieldName );
//since field is static, the "object" is ignored
Resources res = getResources();
int resourceID = f.getInt ( new Object() );
String[] listItems = res.getStringArray( resourceID );
ListView conjugated = (ListView) findViewById(R.id.ListView01);
conjugated.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listItems));
}
Thank you
Yes, sorry it should be R.array or whatever
As for the "unhandled exceptions", if you use eclipse, just do the "recommended fix" and it will add a try/catch for you.
You may have to define some fields outside the try catch block and move some stuff around a bit after eclipse adds the try/catch.
Also, just as an aside, you may want to read a tutorial or two on reflection in Java so what I am saying doesnt sound as new/strange. Not required but it always helps to know a bit of reflection I think

More secure encryption class using salt

Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.
Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc
Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
String salt = getSalt(context);
md.update(salt.getBytes());
byte[] bytes = md.digest(string.getBytes());
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String getSalt(Context context) throws NoSuchAlgorithmException {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String salt = preferences.getString("salt", null);
if (salt == null) {
byte[] saltBytes = new byte[20];
SecureRandom.getInstance("SHA1PRNG").nextBytes(saltBytes);
salt = new String(saltBytes);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("salt", salt).commit();
}
return salt;
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Thanks for sharing, it's quite usefull ! I will include it to my project
Jonny said:
Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.
Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc
Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
String salt = getSalt(context);
md.update(salt.getBytes());
byte[] bytes = md.digest(string.getBytes());
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String getSalt(Context context) throws NoSuchAlgorithmException {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String salt = preferences.getString("salt", null);
if (salt == null) {
byte[] saltBytes = new byte[20];
SecureRandom.getInstance("SHA1PRNG").nextBytes(saltBytes);
salt = new String(saltBytes);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("salt", salt).commit();
}
return salt;
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
Thanks
Gesendet von meinem LG-D855 mit Tapatalk

Pseudo-3D effect with gyroscope

I want to share some codes of a small effect that I implemented in my Android app called Arithmetic Puzzles. This is also a chance for me to listen to other people and make improvements. At the end of this post there is a link to the app so that you can see the code in action.
It is a pseudo-3D effect of the playing board items which are looking like rotating slightly based on your viewing angle when you move the device. The effect is not something of very visible but this small non-disturbing animations usually please the user and make the app look cooler.
Why I call it "pseudo"? Because there is no 3D animation behind, and not even a View animation like rotation around some axis or so. The solution is really simple - I just change the border of the item on gyroscope events which somehow fakes the viewing angle change.
The board item is a simple round rectangle and its border is drawn with a gradient of white color going to transparent. This creates the "fake viewing angle" effect.
So here is our BoardItemView class which is just a simple View:
Code:
public class BoardItemView extends View {
// the color of the board itself (blue)
private int mBoardBack;
// the color of the border (white)
private int mBorderColor;
// the color of the gradient end (transparent)
private int mGradientEndColor;
// constructors
public ToolboxItemView(Context context) {
super(context);
init(context);
}
public ToolboxItemView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
// initialize the colors
Resources r = context.getResources();
mBorderColor = r.getColor(R.color.item_border);
mBoardBack = r.getColor(R.color.item_background);
int transparent = r.getColor(android.R.color.transparent);
setBackgroundColor(transparent);
mGradientEndColor = transparent;
}
As you see, there is nothing special about its initialization. I skipped the other member variables so that it doesn't have any info that is not yet needed for understanding, I will add them later.
Let's go to the onDraw() function:
Code:
...
private static final float RECT_PADDING_PERCENTAGE = 0.05f;
private static final float RECT_RADIUS_PERCENTAGE = 0.1f;
private RectF mRoundRect = new RectF();
private Rect mBounds = new Rect();
private float mRadius = 0.0f;
...
@Override
protected void onDraw(Canvas canvas) {
// step 1: collect information needed for drawing
canvas.getClipBounds(mBounds);
float padding = mBounds.height() * RECT_PADDING_PERCENTAGE;
mRoundRect.set(mBounds);
mRoundRect.inset(padding, padding);
mRadius = RECT_RADIUS_PERCENTAGE * mBounds.height();
...
In the first lines of onDraw() I am taking the clip bounds with getClipBounds() function - I need it to understand where I should do my drawing. My experience showed that it is a good idea to get clip bounds, usually you draw between (0, 0) and (width, height), but I have seen some ugly cases (when I was dealing with Android's Launcher codes) where this is not true.
Then I calculate the round rect parameters, like size and corner radius. As you noticed, no "new" calls in onDraw(), all the needed variables are kept as data members and created when this View is instantiated.
Next comes the drawing of the board itself, nothing special:
Code:
...
private Paint mRectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
...
@Override
protected void onDraw(Canvas canvas) {
...
// step 2: draw the background fill
mRectPaint.setShader(null);
mRectPaint.setDither(false);
mRectPaint.setStyle(Paint.Style.FILL);
mRectPaint.setColor(mBoardBack);
canvas.drawRoundRect(mRoundRect, mRadius, mRadius, mRectPaint);
...
As you can see, I am just drawing a board item as a round rectangle. Before drawing I am setting up the Paint: setting shader to null, dither to false, style to FILL and color to mBoardBack (blue). I will explain the shader and dither in the next step where they are being set. Here I just need to reset (disable) them back. Style is set to FILL so that any shape I paint is also filled with the color of the Paint.
Let's go to the border part, which is interesting:
Code:
...
private LinearGradient mBorderGradient;
...
@Override
protected void onDraw(Canvas canvas) {
...
// step 3: draw the background border
mRectPaint.setStyle(Paint.Style.STROKE);
mRectPaint.setColor(mBorderColor);
createGradient();
mRectPaint.setDither(true);
mRectPaint.setShader(mBorderGradient);
canvas.drawRoundRect(mRoundRect, mRadius, mRadius, mRectPaint);
// step 4: draw the content of a board item here, like text, image, etc...
}
First of all, I am setting the paint style to STROKE. This means that any shape I draw will not be filled with the color, only the border will be drawn. There is also FILL_AND_STROKE style which both draws the border of the shape and fills it with the paint (remember that in previous step we just filled the round rectangle). Since I am not setting the width of the border stroking it will be just one pixel wide. This is enough to see the effect and not big enough for eyes to see the "pseudo"-ness of the 3D effect.
After that I am setting the color of the Paint and then calling a createGradient() function. We will come to that function in a few minutes. Then I am enabling the dither mode on the Paint and setting a shader on it to be the gradient that I just created with that createGradient() function call.
What does all that mean and what is a Shader in Android's Paint system? Its basically quite simple - a Shader is an object from where the Paint gets color information during drawing any shape (except drawing bitmaps). When the shader is null then the Paint object uses the color it was set, otherwise it asks the Shader object what color to use when painting a pixel at some coordinate. As an example you can see a picture acting as a shader and what will happen if a Paint will draw letter 'R' using that shader.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Seems like there are fixed number of shaders in Android, although BitmapShader is covering almost all of the possibilities. In my case I use LinearGradient class which extends Shader class.
TO BE CONTINUED in the thread, seems there is limit on post size...
...CONTINUATION of the original post.
We also set dither to 'true'. It is always a good idea to set dither to true when you are drawing gradients. For more information you can go here where this famous Android Guy is showing some examples of dithering.
Lets go to the createGradient() function:
Code:
...
private Float mXAngle = null;
private Float mYAngle = null;
...
private void createGradient() {
if (mBounds.height() == 0) {
return;
}
int startColor = mBorderColor;
float x0 = mBounds.left;
float y0 = mBounds.bottom;
float x1 = mBounds.right;
float y1 = mBounds.top;
if (mXAngle != null && mYAngle != null) {
if (mXAngle == 0 && mYAngle == 0) {
startColor = mGradientEndColor;
} else {
float h = mBounds.height();
float w = mBounds.width();
float radius = (float) Math.sqrt(h * h + w * w) / 2.0f;
float norm = radius / (float) Math.sqrt(mXAngle * mXAngle + mYAngle * mYAngle);
x0 = mBounds.centerX() + mXAngle * norm;
y0 = mBounds.centerY() + mYAngle * norm;
x1 = mBounds.centerX() - mXAngle * norm;
y1 = mBounds.centerY() - mYAngle * norm;
}
}
mBorderGradient = new LinearGradient(x0, y0, x1, y1,
startColor, mGradientEndColor, Shader.TileMode.CLAMP);
}
The variables mXAngle and mYAngle are set from outside using gyroscope data. We will come to that later. Now think of them as of a vector - they are showing a direction. We are using this direction as a direction of our gradient.
In order to fully define a linear gradient we need 2 (x,y) points on the plane - a start point and end point as shown in the picture below.
Note that these points should be in the coordinate system of the view, that is why are using mBounds variable. The shader mode is set to CLAMP so that outside these bounds the color of the corresponding point is used.
Then comes some math. We set the default "view angle" to the direction from left-bottom to top-right. After that, if there is a direction set, we calculate these 2 gradient points as an intersection of the rectangle's outer circle and the direction line passing through the center of the rectangle. If the direction vector is zero then both gradient colors are set to transparent and no border is drawn (view angle "from top"). First we calculate the radius of rectangle's outer circle - the distance from the center of the rectangle to its corners. Then we calculate a normalization factor and finally put the view direction vector in the center of the rectangle and multiply by normalization factor in order to put its endpoint on the outer circle. The gradient is ready.
In the picture below you can see the result of drawing a round rectangle border with a linear gradient shader:
The final step is to set the "view angle" based on gyroscope values:
Code:
public void onGyroChanged(float xAngle, float yAngle) {
mXAngle = xAngle;
mYAngle = yAngle;
invalidate();
}
This function sets the new angle values and calls invalidate() to redraw self.
The gyroscope processing is out of the scope of this post, so I will just paste the code here. It is mostly copied from Android documentation:
Code:
public class GyroHelper implements SensorEventListener {
private static final float NS2S = 1.0f / 1000000000.0f;
private Display mDisplay;
private boolean mStarted = false;
private SensorManager mManager;
private long mLastTime = 0;
private float mAngleX = 0.0f;
private float mAngleY = 0.0f;
public GyroHelper(Context c) {
mManager = (SensorManager) c.getSystemService(Context.SENSOR_SERVICE);
WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
mDisplay = wm.getDefaultDisplay();
}
public static boolean canBeStarted(Context c) {
SensorManager manager = (SensorManager) c.getSystemService(Context.SENSOR_SERVICE);
return manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null;
}
public void start() {
mStarted = false;
Sensor sensor = mManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (sensor == null) {
return;
}
mStarted = true;
reset();
mManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
}
public void stop() {
mStarted = false;
reset();
mManager.unregisterListener(this);
}
public boolean isStarted() {
return mStarted;
}
public float getXAngle() {
switch (mDisplay.getRotation()) {
case Surface.ROTATION_0: return -mAngleY;
case Surface.ROTATION_90: return -mAngleX;
case Surface.ROTATION_180: return mAngleY;
case Surface.ROTATION_270: return mAngleX;
}
return mAngleX;
}
public float getYAngle() {
switch (mDisplay.getRotation()) {
case Surface.ROTATION_0: return -mAngleX;
case Surface.ROTATION_90: return mAngleY;
case Surface.ROTATION_180: return mAngleX;
case Surface.ROTATION_270: return -mAngleY;
}
return mAngleY;
}
@Override
public void onSensorChanged(SensorEvent event) {
if (mLastTime != 0) {
final float dT = (event.timestamp - mLastTime) * NS2S;
mAngleX += event.values[0] * dT;
mAngleY += event.values[1] * dT;
}
mLastTime = event.timestamp;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private void reset() {
mLastTime = 0;
mAngleX = 0.0f;
mAngleY = 0.0f;
}
}
Somebody needs to start this GyroHelper and periodically call BorderItemView.onGyroChanged(GyroHelper.getXAngle(), GyroHelper.getYHelper()). That can be done right when onSensorChanged() is fired, but it is not a good idea since that can be too often, you might want to have your own timer controlling your frame rate, sensor updates can come 200 times in a second.
Finally, to see this code in action, you can have a look at the app itself, its free:
Google Play:
Direct link:
Download
It would be nice to get some comments and suggestions, let me know your thoughts!

[GUIDE] Text shine effect with gyroscope

I want to share some codes of a small effect that I implemented in my Android app called Arithmetic Puzzles. This is also a chance for me to listen to other people and make improvements. At the end of this post there is a link to the app so that you can see the code in action.
It is a text shining effect which reacts on device movements. It creates a feeling of glass surface of the text which shines and reflects light. Only outline of the text is shining.
Please note that the text in my case was very short - a number with 2 digits - which looks cool. If you will try a longer text then let me know how it looks
I grabbed some parts of my code from its context to put here so if there is something missing or irrelevant then just let me know.
So, here we go! The text shine is done extending a simple View:
Code:
public class EquationView extends View {
...
// the text to be drawn
private String mText;
private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint mTextShinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int mShineColor;
private int mShineNoColor;
...
// constructors
public EquationView(Context context) {
super(context);
init(context);
}
public EquationView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public void initialize(Context context) {
// paints
setupPaint(mTextPaint, R.color.text_color, context); // text color (yellow for me)
setupPaint(mTextShinePaint, R.color.text_shine, context); // shine color (white for me)
mTextShinePaint.setDither(true);
mTextShinePaint.setStyle(Paint.Style.STROKE);
mTextShinePaint.setStrokeJoin(Paint.Join.ROUND);
mTextShinePaint.setStrokeMiter(10);
// colors
mTextShadowColor = context.getResources().getColor(R.color.text_shadow); (#AA454210 for me)
mShineColor = context.getResources().getColor(R.color.text_shine); (white for me)
mShineNoColor = context.getResources().getColor(android.R.color.transparent);
}
private void setupPaint(Paint paint, int colorId, Context context) {
paint.setColor(context.getResources().getColor(colorId));
paint.setTextAlign(Paint.Align.CENTER);
}
The initialization function is setting up the paint objects. Since I am going to use LinearGradient as a shader in my paint, I am setting the dither to true. I have already wrote about it in my previous guide. I am also setting the shine paint style to STROKE so that only the outline of the text is "shining".
The stroke parameters like join and miter are mostly set to make it look prettier.
I also set the text align to CENTER. This has effect during drawing of the text - when I tell the paint to draw a text at some (x, y) point, then x is considered as the center point of the whole text, thus text is centered horizontally on this origin.
Next, let's have a look at the onDraw() function:
Code:
...
private static final float TEXT_HEIGHT = 0.8f;
private static final float SHINE_THICKNESS = 0.015f;
private final float mShadowBlurRadius = 5.0f * getResources().getDisplayMetrics().density; // 5dp
private LinearGradient mShineGradient;
private int mTextShadowColor;
private float mShadowShiftX = 0.0f;
private float mShadowShiftY = 0.0f;
private Rect mBounds = new Rect();
private Rect mTextBounds = new Rect();
...
@Override
protected void onDraw(Canvas canvas) {
// step 1. collect information needed for drawing
canvas.getClipBounds(mBounds);
float centerX = mBounds.centerX();
float h = mBounds.height();
float textSize = h * TEXT_HEIGHT;
float textCenterY = mBounds.top + h * 0.5f;
// step 2. draw the shadows
mTextPaint.setShadowLayer(mShadowBlurRadius, mShadowShiftX, mShadowShiftY, mTextShadowColor);
drawText(mText, centerX, textCenterY, textSize, canvas, mTextPaint);
// step 3. draw the shine
if (mShineGradient != null) {
mTextShinePaint.setShader(mShineGradient);
mTextShinePaint.setStrokeWidth(TextSize * SHINE_THICKNESS);
drawText(mText, centerX, textCenterY, textSize, canvas, mTextShinePaint);
}
// step 4. draw the text
mTextPaint.clearShadowLayer();
drawText(mText, centerX, textCenterY, textSize, canvas, mTextPaint);
}
private void drawText(String text, float centerX, float centerY,
float size, Canvas canvas, Paint paint) {
paint.setTextSize(size);
paint.getTextBounds(text, 0, text.length(), mTextBounds);
canvas.drawText(text, centerX, centerY + mTextBounds.height() / 2.0f - mTextBounds.bottom, paint);
}
In step 1 I collect information for drawing like clip bounds (see previous guide for clip bounds), sizes and positions.
In step 2 I draw the shadows. I also want the shadows to move when device moves (on gyroscope events). I actually draw the text with shadows - the text will be overdrawn in next steps so only shadows will be left from this step. The offsets of the shadows - mShadowShiftX and mShadowShiftY - are updated based on gyroscope data.
In step 3 I draw the shine. I set the LinearGradient mShineGradient as the shader of the paint and then set the stroke width to SHINE_THICKNESS. Then I draw text with that shader. For more information on shaders see my previous guide. The mShineGradient is updated when new gyroscope data is received. We will come to this gradient creation later.
In step 4 I disable the shadows and draw the text again. It will overwrite only the text, not the shadows and not the shine, so I have only the outline shining.
A common drawText() function is used to draw the text. It first sets the text size (font size), then calculates the text bounds using getTextBounds(). This is needed to center the text around the origin point also in vertical direction since Paint.Align.CENTER is aligning only in horizontal direction.
TO BE CONTINUED in the thread, seems there is limit on post size...
CONTINUATION of the guide
Now lets see how is the mShineGradient created. This is done every time we got a new data from gyroscope:
Code:
...
// all the magic numbers here and in below function are results of experiments
private static final float MAX_ANGLE = (float)(Math.PI / 2.0);
private final float mShadowMaxShift = 5.0f * getResources().getDisplayMetrics().density; // 5dp
...
public void gyroChanged(float xAngle, float yAngle) {
// 1. shadows
float loweredMax = MAX_ANGLE / 4;
mShadowShiftX = (xAngle / loweredMax) * mShadowMaxShift;
mShadowShiftY = (yAngle / loweredMax) * mShadowMaxShift;
// put in [-mShadowMaxShift, mShadowMaxShift] range
if (mShadowShiftX > mShadowMaxShift) mShadowShiftX = mShadowMaxShift;
if (mShadowShiftX < -mShadowMaxShift) mShadowShiftX = -mShadowMaxShift;
if (mShadowShiftY > mShadowMaxShift) mShadowShiftY = mShadowMaxShift;
if (mShadowShiftY < -mShadowMaxShift) mShadowShiftY = -mShadowMaxShift;
// 2. shine
float angleX = xAngle / MAX_ANGLE;
float angleY = yAngle / MAX_ANGLE;
// put in [-1, 1] range
if (angleX > 1.0f) angleX = 1.0f;
if (angleX < -1.0f) angleX = -1.0f;
if (angleY > 1.0f) angleY = 1.0f;
if (angleY < -1.0f) angleY = -1.0f;
createShineGradient(angleX, angleY);
// redraw
invalidate();
}
The numbers and formulas are quite experimental, so you can play around to find the best numbers for your case. The meaning and usage of gyroChanged() function is explained in my previous guide.
The basic idea behind is to get the shine position based on device's rotation in X and Y direction. I convert the rotation into a range from -1 to 1 using some max angle that I defined. If both X and Y angles are -1 then the shine line is in the lower left corner of the text, if both are 1 then in upper right corner, otherwise somewhere in between.
Here is the createShineGradient() function:
Code:
...
private static final float SHINE_WIDTH = 0.07f;
private static final float SHINE_BLUR_WIDTH = 0.05f;
...
private void createShineGradient(float relativeX, float relativeY) {
if ((mBounds == null) || (mBounds.width() == 0) || (mBounds.height() == 0)) {
mShineGradient = null;
return;
}
// we want to scale the angles' range and take inner part of
// length 1 this will speed up the shine without sudden stops
final float SPEED_FACTOR = 4.0f;
relativeX *= SPEED_FACTOR;
relativeY *= SPEED_FACTOR;
float boxSize = mBounds.height() * 1.2f; // make the text box a bit bigger
float left = mBounds.centerX() - boxSize / 2.0f;
float top = mBounds.top;
// project the (relativeX, relativeY) point to the diagonal
float relative = (relativeX + relativeY) / 2.0f;
// shift by 0.5 to get a point from (0, 1) range
relative += 0.5f;
int[] colors = {mShineNoColor, mShineNoColor, mShineColor, mShineColor, mShineNoColor, mShineNoColor};
float[] positions = {0.0f, clamp(relative - SHINE_WIDTH - SHINE_BLUR_WIDTH),
clamp(relative - SHINE_WIDTH), clamp(relative + SHINE_WIDTH),
clamp(relative + SHINE_WIDTH + SHINE_BLUR_WIDTH), 1.0f};
mShineGradient = new LinearGradient(left, top + boxSize, left + boxSize, top,
colors, positions, Shader.TileMode.CLAMP);
}
private float clamp(float value) {
if (value < 0.0f) {
return 0;
}
if (value > 1.0f) {
return 1.0f;
}
return value;
}
Again, there are a lot of experimental stuff, you might want to play with it to come to a good solution. The LinearGradient shader is explained in my previous guide. However, here we use more colors so that we can have a white stripe in the middle with small color change gradients on borders. The picture below explains everything:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
The idea is to project the relative angle of the device rotation in X and Y direction to a single point on the View's diagonal through which the shine will pass. This projection should result in continuous and more or less natural movement of the shine line during device rotation, the formula I used is a result of my tries and errors.
When a new gradient is created invalidate() is called and the view redraws itself.
Finally, to see this code in action, you can have a look at the app itself, its free:
Google Play:
Direct link:
Download
It would be nice to get some comments and suggestions, let me know your thoughts!

Categories

Resources