Draw Border on HorizontalScrollView Programmatically - android

I'm trying to draw a border on a HorizontalScrollView programmatically, and fill the inside with a diferent colour. I've tried different aproaches, with no success. I can only draw one thing at a time... Here's the last code i've tried.
private void applyViewBorder(View layout, String borderColor,
String fillColor, int borderWidth) {
if (fillColor == null || borderColor == null)
return;
RectShape rect = new RectShape();
ShapeDrawable rectShapeDrawable = new ShapeDrawable(rect);
Paint paint = rectShapeDrawable.getPaint();
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(borderWidth);
paint.setColor(Color.parseColor(borderColor));
if (android.os.Build.VERSION.SDK_INT < 16) {
layout.setBackgroundDrawable(rectShapeDrawable);
} else {
layout.setBackground(rectShapeDrawable);
}
paint.setStyle(Style.FILL);
paint.setColor(Color.parseColor(fillColor));
if (android.os.Build.VERSION.SDK_INT < 16) {
layout.setBackgroundDrawable(rectShapeDrawable);
} else {
layout.setBackground(rectShapeDrawable);
}
}
I've already searched in stack overflow, with no success too...
Thanks in advance. :)

what you can try is
Create XML called border.xml in project drawable folder as below :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
and than
yourshorizontalscrollview.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
or use this one :
yourshorizontalscrollview.setBackground(getResources().getDrawable(R.drawable.border));

Related

Seekbar With Custom Thumb And Interval Text Android [closed]

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 2 years ago.
Improve this question
I want to achieve like this image. Please help
I've tried to make something similar to what you want :
1 - First add XML of the SeekBar as follows :
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="10dp"
android:max="100"
android:maxHeight="4.0dp"
android:progress="60"/>
2 - Create 2 Drawable files progress_bg.xml & custom_thumb.xml :
progress_bg.xml :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#android:id/background">
<shape android:shape="rectangle">
<corners android:radius="5dp"/>
<solid android:color="#e0e0e0"/>
</shape>
</item>
<item android:id="#android:id/secondaryProgress">
<scale
android:scaleWidth="100%" >
<shape android:shape="rectangle">
<corners android:radius="5dp"/>
<solid android:color="#e0e0e0"/>
</shape>
</scale>
</item>
<item android:id="#android:id/progress">
<scale
android:scaleWidth="100%" >
<shape android:shape="rectangle">
<corners android:radius="5dp"/>
<solid android:color="#2574ff"/>
</shape>
</scale>
</item>
</layer-list>
custom_thumb.xml :
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1.5dp"
android:color="#2574ff" />
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
<solid android:color="#fff" />
<size android:width="25dp" android:height="25dp"/>
</shape>
3 - Now the Java code, we need to change the progressDrawable as well as changing the thumb of SeekBar dynamically each time the SeekBar change their value :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBar seekBar = findViewById(R.id.seekBar);
seekBar.setThumb(getCurrentThumb(seekBar.getProgress()));
seekBar.setProgressDrawable(ResourceUtils.getDrawable(R.drawable.progress_bg));
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekBar.setThumb(getCurrentThumb(seekBar.getProgress()));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
I tried to convert thumb Drawable to Bitmap, so I can write a text on it, here's what I've done :
public Drawable getCurrentThumb(int currentProgress) {
Bitmap writableBitmap = ImageUtils.drawable2Bitmap(ResourceUtils.getDrawable(R.drawable.custom_thumb));
writableBitmap = addText(writableBitmap, currentProgress);
return ImageUtils.bitmap2Drawable(writableBitmap);
}
Add text to Bitmap :
public Bitmap addText(Bitmap src, int currentProgress) {
Bitmap.Config bitmapConfig = src.getConfig();
if (bitmapConfig == null) bitmapConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = src.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(35);
Rect rectangle = new Rect();
paint.getTextBounds(
String.valueOf(currentProgress),
0, // start
String.valueOf(currentProgress).length(),
rectangle
);
canvas.drawText(
String.valueOf(currentProgress),
canvas.getWidth() / 2.0f,
canvas.getHeight() / 2.0f + Math.abs(rectangle.height()) / 2.0f, // y
paint // Paint
);
return bitmap;
}
The used library :
implementation 'com.blankj:utilcodex:1.29.0'

Android Layout transparent layout background with underline

I am trying to have a layout background drawable, which will be only gradient underline with 1-2 dp height and rest is transparent, so the upper part will have the parent's background.
Here is what I have.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android>
<!-- underline color -->
<item>
<shape>
<gradient
android:startColor="#color/colorPrimaryDark"
android:endColor="#FFFFFFFF"
android:centerY="0.5"
android:angle="0"/>
</shape>
</item>
<!-- main color -->
<item android:bottom="2.5dp">
<shape android:shape="rectangle">
<solid android:color="#color/white" />
<padding
android:top="4dp"
android:bottom="4dp" />
</shape>
</item>
If I change the solid color in "main color" to transparent, whole background will be using "underline color" settings.
The technique you use to create a line on the bottom of the view works if the color of the layer overlaying the gradient layer is opaque. What you are trying to do is to apply a transparent layer that replaces (erases) the underlying gradient. That is not how it works: A transparent overlay leaves the underlying color, here a gradient, untouched.
Here is an alternate layer-list drawable that you can use for API 23+:
underline_drawable.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:gravity="bottom">
<shape>
<size android:height="2dp" />
<gradient
android:angle="0"
android:centerY="0.5"
android:endColor="#FFFFFFFF"
android:startColor="#color/colorPrimaryDark" />
</shape>
</item>
</layer-list>
Here is what it looks like:
Prior to API 23, you can use the following custom drawable, but it must be set in code.
GradientUnderline.java
public class GradientUnderline extends Drawable {
private Shader mShader;
private final Paint mPaint;
private int mHeight = -1;
private int mStartColor = Color.BLACK;
private int mEndColor = Color.WHITE;
private int mLastWidth;
public GradientUnderline() {
mPaint = new Paint();
}
public GradientUnderline(int lineHeight, int startColor, int endColor) {
mPaint = new Paint();
mHeight = lineHeight;
mStartColor = startColor;
mEndColor = endColor;
}
#Override
public void draw(#NonNull Canvas canvas) {
if (mShader == null || getBounds().width() != mLastWidth) {
mLastWidth = getBounds().width();
mShader = new LinearGradient(0, 0, getBounds().width(), mHeight, mStartColor,
mEndColor, Shader.TileMode.CLAMP);
mPaint.setShader(mShader);
}
canvas.drawRect(0, getBounds().height() - mHeight, getBounds().width(),
getBounds().height(), mPaint);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(#Nullable ColorFilter colorFilter) {
}
#Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
I missed the availability of android:gravity initially because it is not mentioned on the "Drawable Resources" page. It is mentioned, however, in the LayerDrawable documentation.
Why problem occurs: Shape at first item will draw the gradient in entire region. After setting colour to second item will hide the top item region except ay 2.5dp at bottom. So whenever you set transparent colour to second item it automatically show the top level item that is gradient region..
Here i suggest the way to use but you can set to fixed height in view.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="47dp">
<shape>
<gradient
android:startColor="#color/colorPrimaryDark"
android:endColor="#FFFFFFFF"
android:centerY="0.5"
android:angle="0"/>
</shape>
</item>
</layer-list>
View.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/bottom_line">
</RelativeLayout>
Change size according to your needs..!
OUTPUT

how to add layer list on an user uploaded image?

i want to add effects from my layer-list on an user upload image.In this code i can only do effect on an image from drawable i want to change that to an user upload image
this is my xml file for effect
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/colorPrimary"/>
<item>
<bitmap android:src="#drawable/icn" android:gravity="center" android:alpha="0.1"/>
</item>
<item android:top="300dp"
android:left="0dp"
>
<rotate
android:fromDegrees="-12">
<shape
android:shape="rectangle">
<solid
android:color="?android:colorBackground"/>
</shape>
</rotate>
</item>
this is my xml file for displaying the final image
<ImageView
android:id="#+id/bgImage"
android:layout_width="match_parent"
android:gravity="center"
android:background="#drawable/background"
android:layout_height="290dp"/>
You can construct a LayerDrawable by code instead of xml.
Just new a LayerDrawable and call its addLayer method to add Drawables, and all the properties you set from xml can also be set in code, such as setLayerInset methods.
For example, define the drawable:
<?xml version="1.0" encoding="utf-8"?>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="-12">
<shape
android:shape="rectangle">
<solid
android:color="?android:colorBackground"/>
</shape>
</rotate>
Get the drawable from code:
Drawable myDrawable;
Resources res = getResources();
try {
myDrawable = Drawable.createFromXml(res, res.getXml(R.xml.my_drawable));
} catch (Exception ex) {
Log.e("Error", "Exception loading drawable");
}
Create LayerDrawable and addLayer into it:
LayerDrawable layerDrawable = new LayerDrawable();
layerDrawable.addLayer(userDrawable); // userDrawable is from the user upload image
layerDrawable.addLayer(myDrawable);
You can do it by combine bitmaps of user photo and layer-list drawable.
Here is example:
Bitmap effects = BitmapFactory.decodeResource(context.getResources(), R.drawable.effect_name);
Bitmap[] parts = new Bitmap[2];
parts[0] = userImage; //Bitmap
parts[1] = effects; //Bitmap
Bitmap result = Bitmap.createBitmap(parts[0].getWidth() * 2, parts[0].getHeight() * 2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
for (int i = 0; i < parts.length; i++) {
canvas.drawBitmap(parts[i], parts[i].getWidth() * (i % 2), parts[i].getHeight() * (i / 2), paint);
}
first of all Create a layer list like this
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/background" />
<item
<shape>
<solid/>
<stroke android:width="1dip" android:color="#225786" />
<corners android:radius="10dip"/>
<padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>
</item>
</layer-list>
just want a background:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="#drawable/background"
android:tileMode="repeat" >
</bitmap>
And finally add background on ImageView
<ImageView
android:id="#+id/bgImage"
android:layout_width="match_parent"
android:gravity="center"
android:background="#drawable/background"
android:layout_height="290dp"/>

Enlarge the center of an Android gradient drawable

I created an Android gradient drawable where the top and bottom are black and the center is transparent:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:startColor="#android:color/black"
android:centerColor="#android:color/transparent"
android:endColor="#android:color/black"
android:angle="90"/>
</shape>
The rendered gradient looks like this:
As you can see, the black parts spread to most of the screen. I want the black to show only on a small portion of the top and bottom. Is there a way I can make the transparent center larger, or make the top and bottom black stripes smaller?
I tried playing around with some of the other XML attributes mentioned in the linked GradientDrawable documentation, yet none of them seem to make and difference.
For an XML only solution, you can create a layer-list with two separate gradient objects.
The following code creates two overlapping gradient objects and uses centerY with centerColor to offset the black section. Here, the centerY attributes are set to 0.9 and 0.1, so the black color is restricted to the top and bottom 10% of the view height.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:centerColor="#android:color/transparent"
android:centerY="0.9"
android:endColor="#android:color/black"
android:startColor="#android:color/transparent" />
</shape>
</item>
<item>
<shape>
<gradient
android:angle="90"
android:centerColor="#android:color/transparent"
android:centerY="0.1"
android:endColor="#android:color/transparent"
android:startColor="#android:color/black" />
</shape>
</item>
</layer-list>
For API level 23 or higher, the following solution will also work, using android:height. This solution can work even if you don't know the total height of your view, as long as you know how large you want the gradient to be.
This code creates two separate gradients, each with a height of 60sp, and then uses android:gravity to float the gradients to the top and bottom of the view.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:height="60sp"
android:gravity="top">
<shape android:shape="rectangle">
<gradient
android:angle="90"
android:endColor="#android:color/black"
android:startColor="#android:color/transparent" />
</shape>
</item>
<item
android:height="65sp"
android:gravity="bottom">
<shape android:shape="rectangle">
<gradient
android:angle="90"
android:endColor="#android:color/transparent"
android:startColor="#android:color/black" />
</shape>
</item>
</layer-list>
Thank you #Luksprog for the code help, and #thenaoh for the start of the idea.
The above solutions work and it is nice that they are pure XML. If your gradient is showing with stripes, you may want to try a programmatic solution, like shown in #lelloman's answer, to create a smoother gradient.
Here is how it could be done with a custom Drawable. You can tune the LinearGradient as you want, and then set it as the view's background with view.setBackground(new CustomDrawable());.
public class CustomDrawable extends Drawable {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int[] colors;
private float[] positions;
public CustomDrawable() {
paint.setStyle(Paint.Style.FILL);
this.colors = new int[]{0xff000000, 0xffaaaaaa, 0xffffffff, 0xffaaaaaa, 0xff000000};
this.positions = new float[]{.0f, .2f, .5f, .8f, 1.f};
}
#Override
public void setBounds(int left, int top, int right, int bottom) {
super.setBounds(left, top, right, bottom);
LinearGradient linearGradient = new LinearGradient(left, top,left, bottom, colors, positions, Shader.TileMode.CLAMP);
paint.setShader(linearGradient);
}
#Override
public void draw(#NonNull Canvas canvas) {
canvas.drawRect(getBounds(), paint);
}
#Override
public void setAlpha(#IntRange(from = 0, to = 255) int alpha) {
paint.setAlpha(alpha);
}
#Override
public void setColorFilter(#Nullable ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
}
There is a solution, assuming that you know in advance the height of your view (let's say here 60dp):
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="40dp">
<shape android:shape="rectangle">
<gradient
android:type="linear"
android:angle="90"
android:startColor="#FFFFFF"
android:endColor="#000000"/>
</shape>
</item>
<item
android:top="20dp"
android:bottom="20dp"
android:gravity="center_vertical">
<shape android:shape="rectangle">
<solid android:color="#FFFFFF"/>
</shape>
</item>
<item
android:top="40dp"
android:gravity="bottom">
<shape android:shape="rectangle">
<gradient
android:type="linear"
android:angle="90"
android:startColor="#000000"
android:endColor="#FFFFFF"/>
</shape>
</item>
</layer-list>
But if you don't know the height in advance, another solution would be to make your own custom view, like this:
public class MyView extends ImageView
{
private Paint paint = null;
public MyView(Context context, AttributeSet attrs)
{
super(context, attrs);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
#Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
paint.setShader(getLinearGradient(0, getHeight()));
canvas.drawPaint(paint);
}
private LinearGradient getLinearGradient(float y0, float y1)
{
// colors :
int[] listeColors = new int[3];
listeColors[0] = 0xFF000000;
listeColors[1] = 0xFFFFFFFF;
listeColors[2] = 0xFFFFFFFF;
// positions :
float[] listPositions = new float[3];
listPositions[0] = 0;
listPositions[1] = 0.25F;
listPositions[2] = 1;
// gradient :
return new LinearGradient(0, y0, 0, y0 + (y1 - y0) / 2, listeColors, listPositions, Shader.TileMode.MIRROR);
}
}
Hope it helps.

Rectangle shape with two solid colors

I'd like to create a rectangle shape with two solid colors (horizontally) to achieve something like this:
I heard about layer-list, i though i could use it to contains two rectangle with a different color but it seems that it only lays shapes vertically.
Is there a way to achieve this using lalyer-list or should i use something totally different? I'd like to keep it simple with ability to change the shape colors at runtime.
Thanks.
this will surely draw the shape as per your Requirement :
Adjust size of <item> as you need !
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:left="50dip">
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#0000FF" />
</shape>
</item>
<item android:right="50dip">
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#ff0000" />
</shape>
</item>
</layer-list>
You can create custom drawable for this. Just extend Drawable class.
Here is a sample code which draws a rectangle like you wanted, you can provide any number of colors.
public class ColorBarDrawable extends Drawable {
private int[] themeColors;
public ColorBarDrawable(int[] themeColors) {
this.themeColors = themeColors;
}
#Override
public void draw(Canvas canvas) {
// get drawable dimensions
Rect bounds = getBounds();
int width = bounds.right - bounds.left;
int height = bounds.bottom - bounds.top;
// draw background gradient
Paint backgroundPaint = new Paint();
int barWidth = width / themeColors.length;
int barWidthRemainder = width % themeColors.length;
for (int i = 0; i < themeColors.length; i++) {
backgroundPaint.setColor(themeColors[i]);
canvas.drawRect(i * barWidth, 0, (i + 1) * barWidth, height, backgroundPaint);
}
// draw remainder, if exists
if (barWidthRemainder > 0) {
canvas.drawRect(themeColors.length * barWidth, 0, themeColors.length * barWidth + barWidthRemainder, height, backgroundPaint);
}
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
This will give you two colors half and half vertically. Put this code in a drawable resource.
<item
android:top="320dip">
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#color/red" />
</shape>
</item>
<item android:bottom="320dip">
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#color/yellow" />
</shape>
</item>

Categories

Resources