package com.example.androidview;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DiscretePathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
Paint paintBorder, paintCircle;
Path pathBorder, pathCircle;
Path pathShape;
float segmentLength;
float deviation;
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() {
paintBorder = new Paint();
paintBorder.setColor(Color.BLUE);
paintBorder.setStrokeWidth(20);
paintBorder.setStyle(Paint.Style.FILL_AND_STROKE);
paintCircle = new Paint();
paintCircle.setStrokeWidth(20);
pathBorder = new Path();
pathCircle = new Path();
pathShape = new Path();
pathShape.moveTo(0, 0);
pathShape.lineTo(10, 20);
pathShape.lineTo(20, 0);
pathShape.close();
segmentLength = 30.0f;
deviation = 30.0f;
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.GRAY);
pathBorder.reset();
pathBorder.moveTo(50, 50);
pathBorder.lineTo(50, getHeight()-50);
pathBorder.lineTo(getWidth()-50, getHeight()-50);
pathBorder.lineTo(getWidth()-50, 50);
pathBorder.close();
float radius;
pathCircle.reset();
if(getWidth()>getHeight()){
radius = getHeight()/4;
}else{
radius = getWidth()/4;
}
pathCircle.addCircle(getWidth()/2, getHeight()/2, radius, Direction.CCW);
DiscretePathEffect discretePathEffect =
new DiscretePathEffect(segmentLength, deviation);
paintBorder.setPathEffect(discretePathEffect);
canvas.drawPath(pathBorder, paintBorder);
//fill circle with color
paintCircle.setColor(Color.RED);
paintCircle.setStyle(Paint.Style.FILL);
paintCircle.setPathEffect(discretePathEffect);
canvas.drawPath(pathCircle, paintCircle);
//draw stroke with different color
paintCircle.setColor(Color.BLACK);
paintCircle.setStyle(Paint.Style.STROKE);
paintCircle.setPathEffect(discretePathEffect);
canvas.drawPath(pathCircle, paintCircle);
}
public void setDeviation(int dev){
deviation = (float)dev;
invalidate();
}
public void setSegmentLength(int seglen){
//force segmentLength not 0
if (seglen==0){
seglen = 1;
}
segmentLength = (float)seglen;
invalidate();
}
public void setStrokeWidth(int strwidth){
paintBorder.setStrokeWidth(strwidth);
paintCircle.setStrokeWidth(strwidth);
invalidate();
}
}
Other files, /res/layout/activity_main.xml and MainActivity.java, refer to last post DiscretePathEffect example.
- More examples of drawing path on custom View.
0 Response to "Fill path and stroke with different color"
Posting Komentar