在Android中以编程方式创建平行四边形可绘制对象

4
我正在尝试重新创建在冰淇淋三明治中看到的切换滑块,但是在ICS以下的Android版本中不可用。 我已经完成了滑块的制作,但是目前我正在使用两个平行四边形图像(一个用于关闭状态,一个用于打开状态)。 我想在运行时理想地创建可绘制对象,并根据状态简单地更改其颜色。这将有助于最终的自定义。
我对可绘制对象非常陌生,并希望通过编程方式创建它,因为在我们的框架中我们不使用xml。
创建此对象的原因是平行四边形是一个单一的部分,使得缩放更加易于管理和自定义。
非常感谢任何帮助,并请让我知道您是否需要更多信息!
这是Android切换的外观,我想模仿他们的: ICS Toggle 如果您需要其他详细信息,请告诉我,我希望我以有意义的方式解释了我的需求。
谢谢!

在这种情况下,我总是查看Android源代码以了解其中的情况。为什么不直接使用相关的ICS源代码并将其适应到您自己的项目中呢? - Jerry Brady
他们在实际实现中使用原始图像,没有可用的源。 - HandlerExploit
它们不是梯形吗?或者有一个平行四边形滑动并隐藏其角落吗? - snapfractalpop
嘿,卡梅伦,看起来是个很棒的解决方案,你应该把它作为回答这个问题的答案。 - shecodesthings
1个回答

5

我能够自己回答这个问题...我使用路径来创建可绘制对象,然后将它们拼接在一起创建平行四边形。

public Drawable createThumbDrawable(boolean checked){
    Path path = new Path();
    path.moveTo(0, 0);
    path.lineTo(1, 0);
    path.lineTo(1, 1);
    path.lineTo(0, 1);
    path.close();

    PathShape shape = new PathShape(path, 1, 1);
    ShapeDrawable drawable = new ShapeDrawable(shape);
    if (checked){
        drawable.getPaint().setColor(Color.CYAN);
    }
    else
    {
        drawable.getPaint().setColor(Color.BLACK);
    }
    mThumbLeftDrawable = createLeftThumbDrawable(checked);
    mThumbRightDrawable = createRightThumbDrawable(checked);
    return drawable;
}

public Drawable createLeftThumbDrawable(boolean checked){
    Path path = new Path();
    path.moveTo(0, 25);
    path.lineTo(25, 0);
    path.lineTo(25, 25);
    path.close();

    PathShape shape = new PathShape(path, 25, 25);
    ShapeDrawable drawable = new ShapeDrawable(shape);
    if (checked){
        drawable.getPaint().setColor(Color.CYAN);
    }
    else
    {
        drawable.getPaint().setColor(Color.BLACK);
    }
    return drawable;
}

public Drawable createRightThumbDrawable(boolean checked){
    Path path = new Path();
    path.moveTo(0,0);
    path.lineTo(25, 0);
    path.lineTo(0, 25);
    path.close();

    PathShape shape = new PathShape(path, 25, 25);
    ShapeDrawable drawable = new ShapeDrawable(shape);
    if (checked){
        drawable.getPaint().setColor(Color.CYAN);
    }
    else
    {
        drawable.getPaint().setColor(Color.BLACK);
    }
    return drawable;

}

public void setChecked(boolean checked) {
    //Log.d(TAG, "setChecked("+checked+")");
    boolean lc = checked;
    if (!mTextOnThumb) {
        lc = !checked;
    }

    if (checked){
        mThumbDrawable = createThumbDrawable(checked);//this.getContext().getResources().getDrawable(R.drawable.slide_off);
    }
    else {
        mThumbDrawable = createThumbDrawable(checked);//this.getContext().getResources().getDrawable(R.drawable.slide); 
    }

    super.setChecked(checked);
    mThumbPosition = lc ? getThumbScrollRange() : 0;
    invalidate();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接