gpt4 book ai didi

android - 以编程方式创建一个带有渐变笔触的按钮?

转载 作者:行者123 更新时间:2023-12-05 00:21:20 25 4
gpt4 key购买 nike

我正在创建一个没有填充但有渐变笔触的按钮。作为引用,这是我追求的最终结果:

enter image description here

我想知道如何以编程方式创建具有渐变笔触且无填充的按钮。我看了看GradientDrawable类和 setStroke()里面的方法。似乎没有人允许这样做。有没有办法以编程方式执行此操作,或者根本不可能?

最佳答案

我已经为你尝试了一些东西..
使用mRect.set设置路径和mPath.addRoundRect添加矩形。使用 setShader用于打击目的link

可绘制类:

public class CustomDrawable extends Drawable {
Paint mPaint;
int startColor, endColor, mBorderWidth, mBorderRadius;
RectF mRect;
Path mPath;

public CustomDrawable(int startColor, int endColor, int borderWidth, int borderRadius) {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.FILL);

mPath = new Path();
mPath.setFillType(Path.FillType.EVEN_ODD);

mRect = new RectF();
this.startColor = startColor;
this.endColor = endColor;

mBorderWidth = borderWidth;
mBorderRadius = borderRadius;
}

@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mPath.reset();

// out rect
mRect.set(bounds.left + mBorderWidth, bounds.top + mBorderWidth, bounds.right - mBorderWidth, bounds.bottom - mBorderWidth);
mPath.addRoundRect(mRect, mBorderRadius, mBorderRadius, Path.Direction.CW);

// inner rect
mRect.set(bounds.left + 20, bounds.top + 20, bounds.right - 20, bounds.bottom - 20);
mPath.addRoundRect(mRect, mBorderRadius, mBorderRadius, Path.Direction.CW);
}

@Override
public void draw(@NonNull Canvas canvas) {
// kind of strock
mPaint.setShader(new LinearGradient(0, 0, 0, 100, startColor, endColor, Shader.TileMode.MIRROR));
canvas.drawPath(mPath, mPaint);
}
@Override
public void setAlpha(int alpha) { mPaint.setAlpha(alpha);}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {mPaint.setColorFilter(colorFilter);}
@Override
public int getOpacity() {return PixelFormat.TRANSLUCENT;}
}

主要的 :
Button but = ((Button)findViewById(R.id.but));
but.setBackground(new CustomDrawable(Color.parseColor("#FD659B"),
Color.parseColor("#F76E63"),
but.getPaddingLeft(), 100));

布局 :
<Button
android:id="@+id/but"
android:layout_width="300dp"
android:layout_height="80dp"
android:background="@android:color/transparent"
android:layout_centerInParent="true"
android:text="Signin"/>

关于android - 以编程方式创建一个带有渐变笔触的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50363570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com