下面列出了android.graphics.drawable.ShapeDrawable.ShaderFactory#android.graphics.Shader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void adjustSqureColor(int color) {
int squareWith = ivSquareColor.getWidth();
int squareHight = ivSquareColor.getHeight();
bitmapsqure = Bitmap.createBitmap(squareWith, squareHight, Bitmap.Config.ARGB_8888);
bitmapsqure.eraseColor(Color.GREEN);
ivSquareColor.setImageBitmap(bitmapsqure);
Canvas canvasSquare = new Canvas(bitmapsqure);
Paint mPaint = new Paint();
mPaint.setStrokeWidth(1);
updateMainColors(color, squareWith);
for (int i = 0; i < squareWith; i++) {
int[] colors = new int[2];
colors[0] = mMainColors[i];
colors[1] = Color.BLACK;
Shader shader = new LinearGradient(0, 0, 0, squareHight, colors, null, Shader.TileMode.REPEAT);
mPaint.setShader(shader);
canvasSquare.drawLine(i, 0, i, squareHight, mPaint);
}
mPaint.setShader(null);
}
/**
* Set the bar color. <br>
* <br>
* Its discouraged to use this method.
*
* @param color
*/
public void setColor(int color) {
int x1, y1;
if (mOrientation == ORIENTATION_HORIZONTAL) {
x1 = (mBarLength + mBarPointerHaloRadius);
y1 = mBarThickness;
} else {
x1 = mBarThickness;
y1 = (mBarLength + mBarPointerHaloRadius);
}
Color.colorToHSV(color, mHSVColor);
shader = new LinearGradient(mBarPointerHaloRadius, 0, x1, y1,
new int[] { Color.HSVToColor(0x00, mHSVColor), color }, null,
Shader.TileMode.CLAMP);
mBarPaint.setShader(shader);
calculateColor(mBarPointerPosition);
mBarPointerPaint.setColor(mColor);
if (mPicker != null) {
mPicker.setNewCenterColor(mColor);
}
invalidate();
}
@Override
public void run() {
long currentTime = SystemClock.uptimeMillis();
long delta = currentTime - lastTime;
totalDelta += delta;
float totalPercentage = totalDelta / ((float) speed);
totalPercentage = totalPercentage > 1 ? 1 : totalPercentage;
for (int colorIndex = 0; colorIndex < currentColors.length; colorIndex++) {
currentColors[colorIndex] = (int) (new ArgbEvaluator().evaluate(totalPercentage, colors[(currentGradient + colorIndex) % colors.length], colors[(currentGradient + (colorIndex + 1)) % colors.length]));
}
if (totalPercentage == 1) {
totalDelta = 0;
currentGradient = (currentGradient + 1) % colors.length;
}
Shader shader = new LinearGradient(gradientsPositions[0].x, gradientsPositions[0].y, gradientsPositions[1].x, gradientsPositions[1].y, currentColors, null, Shader.TileMode.CLAMP);
textView.getPaint().setShader(shader);
textView.postInvalidate();
lastTime = currentTime;
}
/**
* 进度
*/
private void drawProgress(Canvas canvas) {
pgPaint.setColor(progressColor);
float right = (progress / maxProgress) * getMeasuredWidth();
pgCanvas.save(Canvas.CLIP_SAVE_FLAG);
pgCanvas.clipRect(0, 0, right, getMeasuredHeight());
pgCanvas.drawColor(progressColor);
pgCanvas.restore();
if(!isStop){
pgPaint.setXfermode(xfermode);
pgCanvas.drawBitmap(flikerBitmap, flickerLeft, 0, pgPaint);
pgPaint.setXfermode(null);
}
//控制显示区域
bitmapShader = new BitmapShader(pgBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
pgPaint.setShader(bitmapShader);
canvas.drawRoundRect(bgRectf, radius, radius, pgPaint);
}
public static void setShadow(View view, Drawable sd) {
RoundRectShape rss = new RoundRectShape(new float[]{12f, 12f, 12f,
12f, 12f, 12f, 12f, 12f}, null, null);
ShapeDrawable sds = new ShapeDrawable(rss);
sds.setShaderFactory(new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, 0, height,
new int[]{Color.parseColor("#e5e5e5"),
Color.parseColor("#e5e5e5"),
Color.parseColor("#e5e5e5"),
Color.parseColor("#e5e5e5")}, new float[]{0,
0.50f, 0.50f, 1}, Shader.TileMode.REPEAT);
return lg;
}
});
LayerDrawable ld = new LayerDrawable(new Drawable[]{sds, sd});
ld.setLayerInset(0, 5, 5, 0, 0); // inset the shadow so it doesn't start right at the left/top
ld.setLayerInset(1, 0, 0, 5, 5); // inset the top drawable so we can leave a bit of space for the shadow to use
view.setBackgroundDrawable(ld);
}
public CustomButton(Context context) {
super(context);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Style.FILL);
paint.setColor(Color.BLACK);
paint.setTextSize(40);
fillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
fillPaint.setStyle(Style.FILL);
fillPaint.setColor(Color.RED);
CornerPathEffect effect = new CornerPathEffect(30);
fillPaint.setPathEffect(effect);
fillPaint.setStyle(Style.FILL_AND_STROKE);
fillPaint.setShader(new LinearGradient(0F, 120, getWidth(),
getHeight(), Color.CYAN, Color.RED, Shader.TileMode.CLAMP));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = getWidth();
mRectHeight = getHeight();
mRectWidth = (int) (mWidth * 0.6 / mRectCount);
mLinearGradient = new LinearGradient(
0,
0,
mRectWidth,
mRectHeight,
Color.YELLOW,
Color.BLUE,
Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
}
@Override public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
if (hidden) {
return;
}
getBounds(boundsRect, parentMatrix, false);
Shader shader;
if (type == GradientType.LINEAR) {
shader = getLinearGradient();
} else {
shader = getRadialGradient();
}
shader.setLocalMatrix(parentMatrix);
paint.setShader(shader);
super.draw(canvas, parentMatrix, parentAlpha);
}
/**
* Set the bar color. <br>
* <br>
* Its discouraged to use this method.
*
* @param color
*/
public void setColor(int color) {
int x1, y1;
if(mOrientation == ORIENTATION_HORIZONTAL) {
x1 = (mBarLength + mBarPointerHaloRadius);
y1 = mBarThickness;
}
else {
x1 = mBarThickness;
y1 = (mBarLength + mBarPointerHaloRadius);
}
Color.colorToHSV(color, mHSVColor);
shader = new LinearGradient(mBarPointerHaloRadius, 0,
x1, y1, new int[] {
Color.HSVToColor(0x00, mHSVColor), color }, null,
Shader.TileMode.CLAMP);
mBarPaint.setShader(shader);
calculateColor(mBarPointerPosition);
mBarPointerPaint.setColor(mColor);
if (mPicker != null) {
mPicker.setNewCenterColor(mColor);
}
invalidate();
}
public Bitmap addGradient(Bitmap originalBitmap){
int width = originalBitmap.getWidth();
int height = originalBitmap.getHeight();
Bitmap updatedBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(updatedBitmap);
canvas.drawBitmap(originalBitmap,0,0,null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0,0,0,height,getResources().getColor(R.color.colorAccent),getResources().getColor(R.color.colorAccent1), Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawRect(0,0,width,height,paint);
return updatedBitmap;
}
/**
* Draw a 'loading' placeholder with a canvas.
*/
private SafePaint getLoadingTilePaint() {
if (mLoadingTilePaint == null && mLoadingBackgroundColor != Color.TRANSPARENT) {
try {
final int tileSize =
mTileProvider.getTileSource() != null ? mTileProvider.getTileSource()
.getTileSizePixels() : 256;
mLoadingTileBitmap =
Bitmap.createBitmap(tileSize, tileSize, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(mLoadingTileBitmap);
canvas.drawColor(mLoadingBackgroundColor);
final int lineSize = tileSize / 16;
for (int a = 0; a < tileSize; a += lineSize) {
canvas.drawLine(0, a, tileSize, a, mLoadingPaint);
canvas.drawLine(a, 0, a, tileSize, mLoadingPaint);
}
mLoadingTilePaint = new SafePaint();
mLoadingTilePaint.setShader(new BitmapShader(mLoadingTileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
} catch (final OutOfMemoryError e) {
Log.e(TAG, "OutOfMemoryError getting loading tile: " + e.toString());
System.gc();
}
}
return mLoadingTilePaint;
}
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
int w = toTransform.getWidth();
int h = toTransform.getHeight();
Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmp);
Shader shader = new BitmapShader(toTransform, Shader.TileMode.MIRROR,
Shader.TileMode.MIRROR);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
paint.setAntiAlias(true);
paint.setShader(shader);
RectF rec = new RectF(0, 0, w, h - (h / 3));
c.drawRect(new RectF(0, (h / 3), w, h), paint);
c.drawRoundRect(rec, cornerRadius, cornerRadius, paint);
toTransform.recycle();
return bmp;
}
public static Bitmap gradientBitmap(Bitmap src, int color1, int color2) {
int width = src.getWidth();
int height = src.getHeight();
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, 0, 0, height, color1, color2, Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawRect(0, 0, width, height, paint);
return result;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (mInteractive && !mExpanded || isAnimating()) {
Rect r = new Rect();
this.getDrawingRect(r);
Paint p = new Paint();
float f = this.getTextSize();
int px = (int)(f / 2);
int bottom = r.bottom - this.getPaddingBottom();
int top = bottom - px;
int start = Color.argb(0, 255, 255, 255);
int end = Color.argb(220, 255, 255, 255);
Shader shader = new LinearGradient(r.left, top, r.left, bottom, start, end, TileMode.CLAMP);
p.setShader(shader);
r.set(r.left, top, r.right, bottom);
p.setStyle(Paint.Style.FILL);
canvas.drawRect(r, p);
}
}
private void setup() {
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
mBitmapPaint = new Paint();
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
updateShaderMatrix();
invalidate();
}
private Bitmap transform(Bitmap source) {
final RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight());
final Bitmap result = createBitmap(source.getWidth(), source.getHeight(),
source.getConfig());
final BitmapShader bitmapShader = new BitmapShader(source, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(bitmapShader);
final Path path = new Path();
path.addRoundRect(rect, roundedCornerRadii, Path.Direction.CCW);
final Canvas canvas = new Canvas(result);
canvas.drawPath(path, paint);
return result;
}
private void resetLinearGradient() {
// our gradient is a simple linear gradient from textColor to reflectionColor. its axis is at the center
// when it's outside of the view, the outer color (textColor) will be repeated (Shader.TileMode.CLAMP)
// initially, the linear gradient is positioned on the left side of the view
linearGradient = new LinearGradient(-view.getWidth(), 0, 0, 0,
new int[]{
primaryColor,
reflectionColor,
primaryColor,
},
new float[]{
0,
0.5f,
1
},
Shader.TileMode.CLAMP
);
paint.setShader(linearGradient);
}
/**
* Set the bar color. <br>
* <br>
* Its discouraged to use this method.
*
* @param color
*/
public void setColor(int color) {
int x1, y1;
if(mOrientation == ORIENTATION_HORIZONTAL) {
x1 = (mBarLength + mBarPointerHaloRadius);
y1 = mBarThickness;
}
else {
x1 = mBarThickness;
y1 = (mBarLength + mBarPointerHaloRadius);
}
Color.colorToHSV(color, mHSVColor);
shader = new LinearGradient(mBarPointerHaloRadius, 0,
x1, y1, new int[] {
color, Color.BLACK }, null, Shader.TileMode.CLAMP);
mBarPaint.setShader(shader);
calculateColor(mBarPointerPosition);
mBarPointerPaint.setColor(mColor);
if (mPicker != null) {
mPicker.setNewCenterColor(mColor);
if(mPicker.hasOpacityBar())
mPicker.changeOpacityBarColor(mColor);
}
invalidate();
}
public RoundedDrawable(Bitmap bitmap) {
mBitmapWidth = bitmap.getWidth();
mBitmapHeight = bitmap.getHeight();
mBitmapRect.set(0, 0, mBitmapWidth, mBitmapHeight);
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapShader.setLocalMatrix(mShaderMatrix);
mBitmapPaint = new Paint();
mBitmapPaint.setStyle(Paint.Style.FILL);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint = new Paint();
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor.getColorForState(getState(), DEFAULT_BORDER_COLOR));
mBorderPaint.setStrokeWidth(mBorderWidth);
}
/**
* @param shadowColor The color of the shadow, e.g. 0x11000000.
*/
public FadingShadow(int shadowColor) {
final int n = SMOOTH_ALGORITHM_INTERPOLATION_POINTS_NUM;
float[] positions = new float[n];
int[] colors = new int[n];
int transparentShadowColor = shadowColor & 0x00FFFFFF;
int shadowAlpha = Color.alpha(shadowColor);
// Piece-wise linear interpolation of the smooth cubic function below.
for (int i = 0; i < n; ++i) {
float x = (float) i / (n - 1);
// Polynomial computation by Estrin's scheme.
float value = (1.0f - 2.2f * x) + (1.8f - 0.6f * x) * (x * x);
positions[i] = x;
colors[i] = (Math.round(shadowAlpha * value) << 24) | transparentShadowColor;
}
mShadowShader = new LinearGradient(0, 0, 0, 1, colors, positions, Shader.TileMode.CLAMP);
}
@Test
public void testParseRadialGradient() throws Exception {
//given
when(picture.beginRecording(anyInt(), anyInt())).thenReturn(canvas);
SVGParser.SVGHandler parserHandler = spy(this.parserHandler);
RadialGradient gradient = mock(RadialGradient.class);
PowerMockito.whenNew(RadialGradient.class).withArguments(
eq(10.1f), eq(4.1f), eq(5.0f), eq(new int[]{-65536}), eq(new float[]{10.1f}), eq(Shader.TileMode.CLAMP)
).thenReturn(gradient);
//when
startSVG(parserHandler);
startElement(parserHandler, attributes(attr("id", "g1"), attr("cx", "10.1"), attr("cy", "4.1"), attr("r", "5.0")), "radialGradient");
startElement(parserHandler, attributes(attr("offset", "10.1"), attr("style", "stop-color:ff0000")), "stop");
endElement(parserHandler, "stop");
endElement(parserHandler, "radialGradient");
startElement(parserHandler, attributes(attr("width", "100"), attr("height", "100"), attr("fill", "url(#g1)")), "rect");
endElement(parserHandler, "rect");
endSVG(parserHandler);
//then
verify(paint).setShader(gradient);
;
}
/**
* Create shader and set shader to mPaintCover
*/
private void createShader() {
if (mWidth == 0)
return;
//if mBitmapCover is null then create default colored cover
if (mBitmapCover == null) {
mBitmapCover = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
mBitmapCover.eraseColor(mCoverColor);
}
mCoverScale = ((float) mWidth) / (float) mBitmapCover.getWidth();
mBitmapCover = Bitmap.createScaledBitmap(mBitmapCover,
(int) (mBitmapCover.getWidth() * mCoverScale),
(int) (mBitmapCover.getHeight() * mCoverScale),
true);
mShader = new BitmapShader(mBitmapCover, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaintCover = new Paint();
mPaintCover.setAntiAlias(true);
mPaintCover.setShader(mShader);
}
public Wave(View v, Bitmap b, int durationMillis, int color) {
bitmap = b;
shader = new BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
paint = new Paint();
paint.setShader(shader);
paint.setAntiAlias(true);
matrix = new Matrix();
durMillis = durationMillis;
viewRef = new WeakReference<>(v);
if (color != 0) {
paint.setColorFilter(new LightingColorFilter(0X02FFFFFF, color));
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
viewWidth = w;
viewHeight = h;
if (viewWidth <= 0 || viewHeight <= 0) return;
int barWidth = (int) (viewWidth * INDICATOR_TO_BAR_WIDTH_RATIO);
centerX = viewWidth / 2;
indicatorRadius = (viewWidth / 2) - borderWidth;
colorPickerRadius = (barWidth / 2) - borderWidth;
colorPickerBody = new RectF(centerX - colorPickerRadius,
borderWidth + colorPickerRadius + indicatorRadius,
centerX + colorPickerRadius,
viewHeight - (borderWidth + colorPickerRadius + indicatorRadius));
LinearGradient gradient = new LinearGradient(0, colorPickerBody.top, 0, colorPickerBody.bottom, colors, null, Shader.TileMode.CLAMP);
paint.setShader(gradient);
if (bitmap != null) {
bitmap.recycle();
}
bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
bitmapCanvas = new Canvas(bitmap);
}
private boolean doFill(Properties atts, HashMap<String, Shader> gradients) {
if ("none".equals(atts.getString("display"))) {
return false;
}
String fillString = atts.getString("fill");
if (fillString != null && fillString.startsWith("url(#")) {
// It's a gradient fill, look it up in our map
String id = fillString.substring("url(#".length(), fillString.length() - 1);
Shader shader = gradients.get(id);
if (shader != null) {
// Util.debug("Found shader!");
shader.printTo(drawInstructions);
drawInstructions.add("paint.setShader(shader);");
drawInstructions.add("paint.setStyle(Paint.Style.FILL);");
return true;
} else {
// Util.debug("Didn't find shader!");
return false;
}
} else {
drawInstructions.add("paint.setShader(null);");
Integer color = atts.getHex("fill");
if (color != null) {
doColor(atts, color, true);
drawInstructions.add("paint.setStyle(Paint.Style.FILL);");
return true;
} else if (atts.getString("fill") == null && atts.getString("stroke") == null) {
// Default is black fill
drawInstructions.add("paint.setStyle(Paint.Style.FILL);");
drawInstructions.add("paint.setColor(0xFF000000);");
return true;
}
}
return false;
}
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap cropped = Bitmap.createBitmap(source, x, y, size, size);
// release source bitmap
if (cropped != source) {
source.recycle();
}
if (radius <= 0) {
// no rounding needed
return cropped;
}
/**
* Round the corners of the image using the radius specified in {@link CropSquareTransform}
*/
// create paint out of the image
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(cropped, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
// create canvas to draw on
Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawRoundRect(new RectF(0, 0, size, size), radius, radius, paint);
// release cropped bitmap
if (output != cropped) {
cropped.recycle();
}
return output;
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2, (mBorderRect.width() - mBorderWidth) / 2);
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width() - mBorderWidth, mBorderRect.height() - mBorderWidth);
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
updateShaderMatrix();
invalidate();
}
public void setImageBitmap(ImageReceiver.BitmapHolder bitmap) {
if (bmp != null) {
bmp.release();
bitmapShader = null;
}
bmp = bitmap;
if (bitmap != null && bitmap.bitmap != null) {
bitmapRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
bitmapShader = new BitmapShader(bmp.bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
roundPaint.setShader(bitmapShader);
}
invalidate();
}
public RoundedDrawable setTileModeX(Shader.TileMode tileModeX) {
if (mTileModeX != tileModeX) {
mTileModeX = tileModeX;
mRebuildShader = true;
invalidateSelf();
}
return this;
}
@Override
public void draw(@NonNull Canvas canvas) {
mRectF.set(getBounds());
mRectF.inset(mInsetX, mInsetY);
if (mBackgroundColors != null) {
mLinearGradient = new LinearGradient(mRectF.left, mRectF.top, mRectF.right, mRectF.bottom, mBackgroundColors, new float[]{0, 1.f}, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
}
canvas.drawRoundRect(mRectF, mCornerRadius, mCornerRadius, mPaint);
}