我需要制作一条水平虚线。看起来像这样:
这就是我在iOS中的表现方式:
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGSize frameSize = size;
CGRect shapeRect = CGRectMake(0.0f, 0.0f, frameSize.width, frameSize.height);
[shapeLayer setBounds: shapeRect];
[shapeLayer setPosition: CGPointMake(frameSize.width / 2, frameSize.height / 2)];
[shapeLayer setFillColor: [[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor: color];
[shapeLayer setLineWidth: 3.0f];
[shapeLayer setLineJoin: kCALineJoinRound];
[shapeLayer setLineDashPattern: [NSArray arrayWithObjects: [NSNumber numberWithInt: 10], [NSNumber numberWithInt: 5], nil]];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect: shapeRect cornerRadius: 0];
[shapeLayer setPath: path.CGPath];
如何在Android中实现类似的效果?
答案 0 :(得分:1)
//更新回答2
我们可以通过java
来解决这个问题
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
Paint paint;
Path path;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(10); // set stroke value as you want
paint.setStyle(Paint.Style.STROKE);
float[] intervals = new float[]{50.0f, 20.0f};
float phase = 0;
DashPathEffect dashPathEffect =
new DashPathEffect(intervals, phase);
paint.setPathEffect(dashPathEffect);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
path = new Path(); // this method to make path for our draw
path.moveTo(50, 50); // x , y value of start point , if you dont any value the default will be (0,0)
path.lineTo(50, 500); // to (x,y) value end point use getMeasuredWidth() to full width in x value
canvas.drawPath(path, paint);
}
}
在您的应用程序中使用它
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<view
android:layout_width="match_parent"
android:layout_height="wrap_content"
class="com.imaadv.testpro.DashedLineView"/>
</RelativeLayout>