Scale selected item in Gallery - android

Do you know how can I scale the selected item in a Gallery? I know that apparently getScale() and getAlpha() were removed from 0.9 SDK. So how could I accomplish the same effect?
Thanks

Maybe it's too late to answer, but I found this question when searching something else.
I did it by having a custom gallery and overriding getChildStaticTransformation() and adding some other things.
Here is an example
private int centerOfGallery;
public CustomGallery(Context context) {
super(context);
init();
}
public CustomGallery(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setStaticTransformationsEnabled(true);
}
private int getCenterWidthOfView(View child) {
return child.getLeft() + child.getWidth() / 2;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
centerOfGallery = (w - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}
#Override
protected boolean getChildStaticTransformation(View child, Transformation t) {
mCamera.save();
final Matrix matrix = t.getMatrix();
final int centerWidthOfChild = getCenterWidthOfView(child);
final int delta = centerOfGallery - centerWidthOfChild;
final float scale = (float)(maxScale - Math.abs(delta) * 0.5f / centerOfGallery);
mCamera.getMatrix(matrix);
matrix.preScale(scale, scale);
matrix.preTranslate(-1, -1);
matrix.postTranslate(1, 1);
mCamera.restore();
if (version >= 15) { // For Jelly Bean hack
child.invalidate();
}
return true;
}
where
maxScale is the maximum scale you want for selected item (e.g. 1.5f)
After that, be careful about the spacing between items in the gallery when scaling them. You can use setSpacing() if necessary.
Hope this helps
Seb

try this
Image in Canvas with touch events

Related

How to make a transparent (alpha) gradient mask to make one layer fade into transparency in Android?

I want to makes one layer fade into the beneath layers (or transparency depends on how you see it) according to a gradient. A so-called transparent (alpha) gradient mask. I am looking for a solution similar to this but on android instead of ios:
I have tried this solution but as mentioned in the comments, the overlay is not making the layer beneath transparent, it only makes it fade to a specified color.
Any suggestions?
You could use Android-FadingEdgeLayout library.
Or here's a subclassed framelayout based on the said lib:
public class AlphaGradientLayout extends FrameLayout {
private static final int DEFAULT_GRADIENT_SIZE_DP = 80;
public static final int FADE_EDGE_TOP = 1;
private static final int DIRTY_FLAG_TOP = 1;
private static final int[] FADE_COLORS = new int[]{Color.TRANSPARENT, Color.BLACK};
private boolean fadeTop;
private int gradientSizeTop;
private Paint gradientPaintTop;
private Rect gradientRectTop;
private int gradientDirtyFlags;
public AlphaGradientLayout(Context context) {
super(context);
init(null, 0);
}
public AlphaGradientLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public AlphaGradientLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, 0);
}
private void init(AttributeSet attrs, int defStyleAttr) {
int defaultSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_GRADIENT_SIZE_DP,
getResources().getDisplayMetrics());
if (attrs != null) {
TypedArray arr = getContext().obtainStyledAttributes(attrs, R.styleable.AlphaGradientLayout, defStyleAttr, 0);
int flags = arr.getInt(R.styleable.FadingEdgeLayout_fel_edge, 0);
fadeTop = (flags & FADE_EDGE_TOP) == FADE_EDGE_TOP;
gradientSizeTop = arr.getDimensionPixelSize(R.styleable.FadingEdgeLayout_fel_size_top, defaultSize);
if (fadeTop && gradientSizeTop > 0) {
gradientDirtyFlags |= DIRTY_FLAG_TOP;
}
arr.recycle();
} else {
gradientSizeTop = defaultSize;
}
PorterDuffXfermode mode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
gradientPaintTop = new Paint(Paint.ANTI_ALIAS_FLAG);
gradientPaintTop.setXfermode(mode);
gradientRectTop = new Rect();
}
#Override
public void setPadding(int left, int top, int right, int bottom) {
if (getPaddingTop() != top) {
gradientDirtyFlags |= DIRTY_FLAG_TOP;
}
super.setPadding(left, top, right, bottom);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (h != oldh) {
gradientDirtyFlags |= DIRTY_FLAG_TOP;
}
}
#Override
protected void dispatchDraw(Canvas canvas) {
int newWidth = getWidth(), newHeight = getHeight();
boolean fadeAnyEdge = fadeTop;
if (getVisibility() == GONE || newWidth == 0 || newHeight == 0 || !fadeAnyEdge) {
super.dispatchDraw(canvas);
return;
}
if ((gradientDirtyFlags & DIRTY_FLAG_TOP) == DIRTY_FLAG_TOP) {
gradientDirtyFlags &= ~DIRTY_FLAG_TOP;
int actualHeight = getHeight() - getPaddingTop() - getPaddingBottom();
int size = Math.min(gradientSizeTop, actualHeight);
int l = getPaddingLeft();
int t = getPaddingTop();
int r = getWidth() - getPaddingRight();
int b = t + size;
gradientRectTop.set(l, t, r, b);
LinearGradient gradient = new LinearGradient(l, t, l, b, FADE_COLORS, null, Shader.TileMode.CLAMP);
gradientPaintTop.setShader(gradient);
}
int count = canvas.saveLayer(0.0f, 0.0f, (float) getWidth(), (float) getHeight(), null, Canvas.ALL_SAVE_FLAG);
super.dispatchDraw(canvas);
if (fadeTop && gradientSizeTop > 0) {
canvas.drawRect(gradientRectTop, gradientPaintTop);
}
canvas.restoreToCount(count);
}
}
Then move the items that you want faded inside this layout
And here's what you should get

Align an image to the bottom of an ImageView [duplicate]

I have an ImageView which is displaying a png that has a bigger aspect ratio than that of the device (vertically speaking - meaning its longer). I want to display this while maintaining aspect ratio, matching the width of the parent, and pinning the imageview to the top of the screen.
The problem i have with using CENTER_CROP as the scale type is that it will (understandable) center the scaled image instead of aligning the top edge to the top edge f the image view.
The problem with FIT_START is that the image will fit the screen height and not fill the width.
I have solved this problem by using a custom ImageView and overriding onDraw(Canvas) and handeling this manually using the canvas; the problem with this approach is that 1) I'm worried there may be a simpler solution, 2) I am getting a VM mem exception when calling super(AttributeSet) in the constructor when trying to set a src img of 330kb when the heap has 3 mb free (with a heap size of 6 mb) and cant work out why.
Any ideas / suggestions / solutions are much welcome :)
Thanks
p.s. i thought that a solution may be to use a matrix scale type and do it myself, but that seems to to be the same or more work than my current solution!
Ok, I have a working solution. The prompt from Darko made me look again at the ImageView class (thanks) and have applied the transformation using a Matrix (as i originally suspected but did not have success on my first attempt!). In my custom imageView class I call setScaleType(ScaleType.MATRIX) after super() in the constructor, and have the following method.
#Override
protected boolean setFrame(int l, int t, int r, int b)
{
Matrix matrix = getImageMatrix();
float scaleFactor = getWidth()/(float)getDrawable().getIntrinsicWidth();
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
return super.setFrame(l, t, r, b);
}
I have placed int in the setFrame() method as in ImageView the call to configureBounds() is within this method, which is where all the scaling and matrix stuff takes place, so seems logical to me (say if you disagree)
Below is the super.setFrame() method from the AOSP (Android Open Source Project)
#Override
protected boolean setFrame(int l, int t, int r, int b) {
boolean changed = super.setFrame(l, t, r, b);
mHaveFrame = true;
configureBounds();
return changed;
}
Find the full class src here
Here is my code for centering it at the bottom.
BTW in Dori's Code is a little bug: Since the super.frame() is called at the very end, the getWidth() method might return the wrong value.
If you want to center it at the top simply remove the postTranslate line and you're done.
The nice thing is that with this code you can move it anywhere you want. (right, center => no problem ;)
public class CenterBottomImageView extends ImageView {
public CenterBottomImageView(Context context) {
super(context);
setup();
}
public CenterBottomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public CenterBottomImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setup();
}
private void setup() {
setScaleType(ScaleType.MATRIX);
}
#Override
protected boolean setFrame(int frameLeft, int frameTop, int frameRight, int frameBottom) {
if (getDrawable() == null) {
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);
}
float frameWidth = frameRight - frameLeft;
float frameHeight = frameBottom - frameTop;
float originalImageWidth = (float)getDrawable().getIntrinsicWidth();
float originalImageHeight = (float)getDrawable().getIntrinsicHeight();
float usedScaleFactor = 1;
if((frameWidth > originalImageWidth) || (frameHeight > originalImageHeight)) {
// If frame is bigger than image
// => Crop it, keep aspect ratio and position it at the bottom and center horizontally
float fitHorizontallyScaleFactor = frameWidth/originalImageWidth;
float fitVerticallyScaleFactor = frameHeight/originalImageHeight;
usedScaleFactor = Math.max(fitHorizontallyScaleFactor, fitVerticallyScaleFactor);
}
float newImageWidth = originalImageWidth * usedScaleFactor;
float newImageHeight = originalImageHeight * usedScaleFactor;
Matrix matrix = getImageMatrix();
matrix.setScale(usedScaleFactor, usedScaleFactor, 0, 0); // Replaces the old matrix completly
//comment matrix.postTranslate if you want crop from TOP
matrix.postTranslate((frameWidth - newImageWidth) /2, frameHeight - newImageHeight);
setImageMatrix(matrix);
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);
}
}
Beginner tip: If it plain doesn't work, you likely have to extends androidx.appcompat.widget.AppCompatImageView rather than ImageView
You don't need to write a Custom Image View for getting the TOP_CROP functionality. You just need to modify the matrix of the ImageView.
Set the scaleType to matrix for the ImageView:
<ImageView
android:id="#+id/imageView"
android:contentDescription="Image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/image"
android:scaleType="matrix"/>
Set a custom matrix for the ImageView:
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
final Matrix matrix = imageView.getImageMatrix();
final float imageWidth = imageView.getDrawable().getIntrinsicWidth();
final int screenWidth = getResources().getDisplayMetrics().widthPixels;
final float scaleRatio = screenWidth / imageWidth;
matrix.postScale(scaleRatio, scaleRatio);
imageView.setImageMatrix(matrix);
Doing this will give you the TOP_CROP functionality.
This example works with images that is loaded after creation of object + some optimization.
I added some comments in code that explain what's going on.
Remember to call:
imageView.setScaleType(ImageView.ScaleType.MATRIX);
or
android:scaleType="matrix"
Java source:
import com.appunite.imageview.OverlayImageView;
public class TopAlignedImageView extends ImageView {
private Matrix mMatrix;
private boolean mHasFrame;
#SuppressWarnings("UnusedDeclaration")
public TopAlignedImageView(Context context) {
this(context, null, 0);
}
#SuppressWarnings("UnusedDeclaration")
public TopAlignedImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
#SuppressWarnings("UnusedDeclaration")
public TopAlignedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mHasFrame = false;
mMatrix = new Matrix();
// we have to use own matrix because:
// ImageView.setImageMatrix(Matrix matrix) will not call
// configureBounds(); invalidate(); because we will operate on ImageView object
}
#Override
protected boolean setFrame(int l, int t, int r, int b)
{
boolean changed = super.setFrame(l, t, r, b);
if (changed) {
mHasFrame = true;
// we do not want to call this method if nothing changed
setupScaleMatrix(r-l, b-t);
}
return changed;
}
private void setupScaleMatrix(int width, int height) {
if (!mHasFrame) {
// we have to ensure that we already have frame
// called and have width and height
return;
}
final Drawable drawable = getDrawable();
if (drawable == null) {
// we have to check if drawable is null because
// when not initialized at startup drawable we can
// rise NullPointerException
return;
}
Matrix matrix = mMatrix;
final int intrinsicWidth = drawable.getIntrinsicWidth();
final int intrinsicHeight = drawable.getIntrinsicHeight();
float factorWidth = width/(float) intrinsicWidth;
float factorHeight = height/(float) intrinsicHeight;
float factor = Math.max(factorHeight, factorWidth);
// there magic happen and can be adjusted to current
// needs
matrix.setTranslate(-intrinsicWidth/2.0f, 0);
matrix.postScale(factor, factor, 0, 0);
matrix.postTranslate(width/2.0f, 0);
setImageMatrix(matrix);
}
#Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
#Override
public void setImageResource(int resId) {
super.setImageResource(resId);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
#Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
// We have to recalculate image after chaning image
setupScaleMatrix(getWidth(), getHeight());
}
// We do not have to overide setImageBitmap because it calls
// setImageDrawable method
}
Based on Dori I'm using a solution which either scales the image based on the width or height of the image to always fill the surrounding container. This allows scaling an image to fill the whole available space using the top left point of the image rather than the center as origin (CENTER_CROP):
#Override
protected boolean setFrame(int l, int t, int r, int b)
{
Matrix matrix = getImageMatrix();
float scaleFactor, scaleFactorWidth, scaleFactorHeight;
scaleFactorWidth = (float)width/(float)getDrawable().getIntrinsicWidth();
scaleFactorHeight = (float)height/(float)getDrawable().getIntrinsicHeight();
if(scaleFactorHeight > scaleFactorWidth) {
scaleFactor = scaleFactorHeight;
} else {
scaleFactor = scaleFactorWidth;
}
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
return super.setFrame(l, t, r, b);
}
I hope this helps - works like a treat in my project.
None of these solutions worked for me, because I wanted a class that supported an arbitrary crop from either the horizontal or vertical direction, and I wanted it to allow me to change the crop dynamically. I also needed Picasso compatibility, and Picasso sets image drawables lazily.
My implementation is adapted directly from ImageView.java in the AOSP. To use it, declare like so in XML:
<com.yourapp.PercentageCropImageView
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="matrix"/>
From source, if you wish to have a top crop, call:
imageView.setCropYCenterOffsetPct(0f);
If you wish to have a bottom crop, call:
imageView.setCropYCenterOffsetPct(1.0f);
If you wish to have a crop 1/3 of the way down, call:
imageView.setCropYCenterOffsetPct(0.33f);
Furthermore, if you elect to use another crop method, like fit_center, you may do so and none of this custom logic will be triggered. (Other implementations ONLY let you use their cropping methods).
Lastly, I added a method, redraw(), so if you elect to change your crop method/scaleType dynamically in code, you can force the view to redraw. For example:
fullsizeImageView.setScaleType(ScaleType.FIT_CENTER);
fullsizeImageView.redraw();
To go back to your custom top-center-third crop, call:
fullsizeImageView.setScaleType(ScaleType.MATRIX);
fullsizeImageView.redraw();
Here is the class:
/*
* Adapted from ImageView code at:
* http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/android/widget/ImageView.java
*/
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class PercentageCropImageView extends ImageView{
private Float mCropYCenterOffsetPct;
private Float mCropXCenterOffsetPct;
public PercentageCropImageView(Context context) {
super(context);
}
public PercentageCropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PercentageCropImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public float getCropYCenterOffsetPct() {
return mCropYCenterOffsetPct;
}
public void setCropYCenterOffsetPct(float cropYCenterOffsetPct) {
if (cropYCenterOffsetPct > 1.0) {
throw new IllegalArgumentException("Value too large: Must be <= 1.0");
}
this.mCropYCenterOffsetPct = cropYCenterOffsetPct;
}
public float getCropXCenterOffsetPct() {
return mCropXCenterOffsetPct;
}
public void setCropXCenterOffsetPct(float cropXCenterOffsetPct) {
if (cropXCenterOffsetPct > 1.0) {
throw new IllegalArgumentException("Value too large: Must be <= 1.0");
}
this.mCropXCenterOffsetPct = cropXCenterOffsetPct;
}
private void myConfigureBounds() {
if (this.getScaleType() == ScaleType.MATRIX) {
/*
* Taken from Android's ImageView.java implementation:
*
* Excerpt from their source:
} else if (ScaleType.CENTER_CROP == mScaleType) {
mDrawMatrix = mMatrix;
float scale;
float dx = 0, dy = 0;
if (dwidth * vheight > vwidth * dheight) {
scale = (float) vheight / (float) dheight;
dx = (vwidth - dwidth * scale) * 0.5f;
} else {
scale = (float) vwidth / (float) dwidth;
dy = (vheight - dheight * scale) * 0.5f;
}
mDrawMatrix.setScale(scale, scale);
mDrawMatrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));
}
*/
Drawable d = this.getDrawable();
if (d != null) {
int dwidth = d.getIntrinsicWidth();
int dheight = d.getIntrinsicHeight();
Matrix m = new Matrix();
int vwidth = getWidth() - this.getPaddingLeft() - this.getPaddingRight();
int vheight = getHeight() - this.getPaddingTop() - this.getPaddingBottom();
float scale;
float dx = 0, dy = 0;
if (dwidth * vheight > vwidth * dheight) {
float cropXCenterOffsetPct = mCropXCenterOffsetPct != null ?
mCropXCenterOffsetPct.floatValue() : 0.5f;
scale = (float) vheight / (float) dheight;
dx = (vwidth - dwidth * scale) * cropXCenterOffsetPct;
} else {
float cropYCenterOffsetPct = mCropYCenterOffsetPct != null ?
mCropYCenterOffsetPct.floatValue() : 0f;
scale = (float) vwidth / (float) dwidth;
dy = (vheight - dheight * scale) * cropYCenterOffsetPct;
}
m.setScale(scale, scale);
m.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));
this.setImageMatrix(m);
}
}
}
// These 3 methods call configureBounds in ImageView.java class, which
// adjusts the matrix in a call to center_crop (android's built-in
// scaling and centering crop method). We also want to trigger
// in the same place, but using our own matrix, which is then set
// directly at line 588 of ImageView.java and then copied over
// as the draw matrix at line 942 of ImageVeiw.java
#Override
protected boolean setFrame(int l, int t, int r, int b) {
boolean changed = super.setFrame(l, t, r, b);
this.myConfigureBounds();
return changed;
}
#Override
public void setImageDrawable(Drawable d) {
super.setImageDrawable(d);
this.myConfigureBounds();
}
#Override
public void setImageResource(int resId) {
super.setImageResource(resId);
this.myConfigureBounds();
}
public void redraw() {
Drawable d = this.getDrawable();
if (d != null) {
// Force toggle to recalculate our bounds
this.setImageDrawable(null);
this.setImageDrawable(d);
}
}
}
Maybe go into the source code for the image view on android and see how it draws the center crop etc.. and maybe copy some of that code into your methods. i don't really know for a better solution than doing this. i have experience manually resizing and cropping the bitmap (search for bitmap transformations) which reduces its actual size but it still creates a bit of an overhead in the process.
public class ImageViewTopCrop extends ImageView {
public ImageViewTopCrop(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}
public ImageViewTopCrop(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
public ImageViewTopCrop(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setScaleType(ScaleType.MATRIX);
}
#Override
protected boolean setFrame(int l, int t, int r, int b) {
computMatrix();
return super.setFrame(l, t, r, b);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
computMatrix();
}
private void computMatrix() {
Matrix matrix = getImageMatrix();
float scaleFactor = getWidth() / (float) getDrawable().getIntrinsicWidth();
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
}
}
If you are using Fresco (SimpleDraweeView) you can easily do it with:
PointF focusPoint = new PointF(0.5f, 0f);
imageDraweeView.getHierarchy().setActualImageFocusPoint(focusPoint);
This one would be for a top crop.
More info at Reference Link
There are 2 problems with the solutions here:
They do not render in the Android Studio layout editor (so you can preview on various screen sizes and aspect ratios)
It only scales by width, so depending on the aspect ratios of the device and the image, you can end up with an empty strip on the bottom
This small modification fixes the problem (place code in onDraw, and check width and height scale factors):
#Override
protected void onDraw(Canvas canvas) {
Matrix matrix = getImageMatrix();
float scaleFactorWidth = getWidth() / (float) getDrawable().getIntrinsicWidth();
float scaleFactorHeight = getHeight() / (float) getDrawable().getIntrinsicHeight();
float scaleFactor = (scaleFactorWidth > scaleFactorHeight) ? scaleFactorWidth : scaleFactorHeight;
matrix.setScale(scaleFactor, scaleFactor, 0, 0);
setImageMatrix(matrix);
super.onDraw(canvas);
}
Simplest Solution: Clip the image
#Override
public void draw(Canvas canvas) {
if(getWidth() > 0){
int clipHeight = 250;
canvas.clipRect(0,clipHeight,getWidth(),getHeight());
}
super.draw(canvas);
}

How to display separators in Android SeekBar?

I have added a SeekBar to one of my fragments. Struggling to add white lines(divider) as shown in above SeekBar. Any clue ? Is there any property I can set for this?
Below is what I have done on a basic level. You will need to make it dynamic to taste:
public class SegmentedSeekBar extends android.support.v7.widget.AppCompatSeekBar {
private Paint progressPaint;
public SegmentedSeekBar(Context context) {
super(context);
init();
}
public SegmentedSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SegmentedSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
progressPaint = new Paint();
progressPaint.setStyle(Paint.Style.FILL_AND_STROKE);
progressPaint.setColor(Color.LTGRAY);
progressPaint.setStrokeWidth(2.0f);
}
#Override
protected synchronized void onDraw(Canvas canvas) {
int halfHeight = getHeight() / 2;
int pos;
float smallH = 10;
float div = (getWidth() - getPaddingRight() - getPaddingLeft()) / (getMax());
for (int i = 1; i < getMax(); i++) {
pos = (int) (div * i) + getPaddingLeft();
canvas.drawLine(
pos + 1.0f,
halfHeight - (halfHeight / 2.0f),
pos + 1.0f,
halfHeight + (halfHeight / 2.0f),
progressPaint);
}
super.onDraw(canvas);
}
}
Best way to done your requirement is add empty view(3 View) over seek bar. create view with match_parent height , 2dp width over seek-bar.
For more info see the link Seek bar with divider

Display a grid using Canvas in Android

I'm trying to display a grid in my Android application. I'm using the "onDraw" method of a custom view I created for this purpose.
The problem is that the result is very strange, not all lines are drawn and some artifacts are visible. May I have your help to solve this?
Here's the code I use:
public class GridView extends View {
private int cellHeight;
private int cellWidth;
private int cellRows = 16;
private int cellColumns = 16;
private Paint lines = new Paint();
public GridView(Context context) {
super(context);
init();
}
public GridView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
lines.setStyle(Paint.Style.FILL_AND_STROKE);
lines.setColor(Color.BLACK);
cellWidth = getWidth() / cellColumns;
cellHeight = getHeight() / cellRows;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
cellWidth = getWidth() / cellColumns;
cellHeight = getHeight() / cellRows;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
for (int i = 0; i < cellRows; i++)
{
canvas.drawLine(0, i * cellHeight, getWidth(), i * cellHeight,
lines);
}
for (int i = 0; i < cellColumns; i++)
{
canvas.drawLine(i * cellWidth, 0, i * cellWidth, getHeight(),
lines);
}
}
}
This is what I get in EMULATOR:
http://hpics.li/ca14cd1
Moreover, in Android preview (when designing activity), I can see the result expected:
http://hpics.li/7b97afb
The problem occurs when the application is really started.

Painting harmonic waves Android

I am making an app that looks like the pic below, the bottom harmonic wave doesn't change but the top one will by setting the amplitude, omega, omega inverse and phi.
I have x and y lines but I cant seem figure out how to even paint the bottom wave, y = sin(x). I have searched and tried to do it but have failed. Can anyone help or give direction to a resource that will help?
This is a simple example drawing two sine waves, taking care of view size changes, some axis scaling and simulation stepping.
<com.pixdart.view.HarmonicCustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DDD"/>
public class HarmonicCustomView extends View {
private Paint mPaint = new Paint();
private RectF mRectF = new RectF();
private float scaleY, scaleX;
public static final float STEP_X = 0.1f;
public static final int PERIODS_TO_SHOW = 5;
public HarmonicCustomView(Context context) {
super(context);
initialize();
}
public HarmonicCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public HarmonicCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mRectF.set(0, 0, w, h);
mRectF.inset(mRectF.width() * 0.1f, mRectF.height() * 0.1f);
scaleX = (float) (2 * Math.PI * PERIODS_TO_SHOW / mRectF.width());
scaleY = mRectF.height() / 6;
}
public void initialize() {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(2f);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(0xFFFF0000);
for (float x = 0; x < mRectF.width(); x += STEP_X) {
float y = (float) (Math.sin(x * scaleX)) * scaleY;
canvas.drawPoint(x + mRectF.left, y + mRectF.top + scaleY, mPaint);
}
mPaint.setColor(0xFF0000FF);
for (float x = 0; x < mRectF.width(); x += STEP_X) {
float y = (float) (Math.sin(x * scaleX)) * scaleY;
canvas.drawPoint(x + mRectF.left, y + mRectF.top + scaleY * 5, mPaint);
}
}
}

Categories

Resources